Synthèse automatique
Guide la rédaction et le refactoring de code TypeScript/JavaScript en appliquant les standards de Metabase, avec une interdiction stricte de `any` et un fort accent sur le durcissement des types.
Points forts
- Règle explicite et vérifiable : aucun `any` nouveau, avec vérification obligatoire via `bun run type-check-pure`
- Conseils concrets de modélisation : `satisfies`, `unknown` affiné, génériques, `Partial`/`Pick`/`Record` avant les casts
- Encadre les casts inévitables avec une justification commentée et interdit le placeholder FIXME historique
- Réutilisation des types canoniques de `metabase-types/api` et centralisation des type guards
Limites
- Très spécifique à la base de code Metabase (chemins, commandes bun, règles de lint internes)
- Suppose l'accès aux fichiers partagés référencés (`@./../_shared/...`) pour être pleinement applicable
- Ne couvre pas les tests, le style de formatage ni l'architecture au-delà du typage
À utiliser lorsqu'on écrit ou refactorise du TypeScript/TSX dans un projet Metabase et qu'on veut garantir l'absence de `any` et des types précis.
À éviter sur un projet TypeScript hors Metabase, où les conventions, chemins et commandes de vérification diffèrent.
Analyse de sécurité
SûrThe skill is a pure coding-standards/style guide for TypeScript/JavaScript. It declares no tools, contains no shell commands, network calls, file mutations, or secret handling. The only executable instruction is running a project type-check (`bun run type-check-pure`), which is a benign, standard verification step. The `@./../_shared/*.md` includes just reference sibling documentation and introduce no execution surface.
Aucun point d'attention détecté
Comment cette analyse est faiteExemples
Refactor this React component to remove the `as any` cast and the implicit any parameters, then run bun run type-check-pure to verify.Model this component's loading/success/error states as a discriminated union and exhaust it with ts-pattern's .exhaustive().Replace these locally re-declared field types with the canonical ones from metabase-types/api and key the map by FieldId.name: typescript-write description: Write TypeScript and JavaScript code following Metabase coding standards and best practices. Use when developing or refactoring TypeScript/JavaScript code.
TypeScript/JavaScript Development Skill
@./../_shared/development-workflow.md @./../_shared/typescript-commands.md @./../_shared/react-redux-patterns.md
No any — hard rule
- New code must not introduce
any, explicit or implicit. Noanyannotations, noas any/as unknown as, no untyped parameters or returns that inferany, no implicitly-anydestructures or array/object literals. - Untyped third-party / boundary values must be typed at the boundary (a declared type,
unknown+ type guard, or a small typed wrapper) — never letanypropagate inward. - Mandatory type verification. Before finishing a TS/TSX change, run
bun run type-check-pure. If TypeScript LSP tools are available, also inspect changed symbols with hover and go-to-definition; otherwise skip LSP check.
Type tightening
- Avoid type casts and loose
unknown— fix the signature instead. - If a function only needs one field of a wide object, accept that field — not the wide object. The cast often disappears once the signature is right.
- Reach for
Partial<T>,Pick<T, K>,Record<K, V>, and generics before reaching for a cast. - Prefer making props/components generic (
<T>) when a value flows through unchanged and the caller knows the type. - Prefer
unknownover loose typing and narrow before use — anunknownvalue forces a guard at the point of use. satisfiesfor object literals that must conform without widening (config objects, lookup maps, discriminated literals) — better than: T(widens) oras T(unsafe).- Avoid non-null assertions (
!). Prefer a guard, early return, or?.. Use!only when non-nullness is provably true and localized, with a comment. - No redundant runtime coercion — don't wrap already-typed values in
Number()/String()/Boolean(). - Type guards belong in
frontend/src/metabase-types/guards/. Do not redefine them locally. - A cast you can't avoid needs a real justification comment. The
metabase/no-unjustified-type-castsrule accepts any preceding comment — state the actual reason the cast is safe. NEVER write the legacy// Unjustified type cast. FIXMEplaceholder; it exists only on casts that predated the rule, and copying it sneaks an unjustified cast past the linter. If you can't articulate why the cast is correct, the cast is wrong — fix the types.
Type modeling
- Reuse existing types; don't re-declare them. Use canonical IDs and domain entity types from
metabase-types/api(FieldId,TableId,ConcreteTableId,SchemaName, …) and key data structures by them (new Map<ConcreteTableId, …>()). Don't duplicate generated/API types — compose or derive (Pick,Omit, indexed accessSomeType["field"],ReturnType). - Use generics to allow TypeScript to infer correct types when creating functions and components that need to be reusable and type-safe. Don't hesitate to introduce complex generics if they allow to derive types automatically instead of manual narrowing.
- Model the actual data contract; keep types narrow. Optional
field?: Tfor a key that may be absent,field: T | undefinedonly when the key is always present but the value may be undefined,| nullfor explicit API nulls. Prefer domain unions over broadstring/number/ looseRecord. - Refer to API implementation when defining or refining types to ensure they match the actual data structure. When considering a type cast, first consider if the type should be refined to match the actual data structure.
- Discriminated unions for variant state, with exhaustive checks. Model "one of N shapes" as a union with a literal discriminant rather than a bag of optional fields, and exhaust it with ts-pattern's
.exhaustive()so adding a variant becomes a compile error:import { match } from "ts-pattern"; const result = match(status) .with({ type: "loading" }, () => <Spinner />) .with({ type: "error", error: P.select() }, (error) => <Error message={error.message} />) .with({ type: "success", data: P.select() }, (data) => <Content data={data} />) .exhaustive(); // Compile-time guarantee all cases handled - Derive union types from constants (
as const+typeof/keyof) so the type and the values can't drift. readonly/ immutability where mutation isn't intended — component props, shared constants, exported config. Preferreadonly T[]/ReadonlyArray<T>for inputs you don't mutate.- Type async and error states explicitly (a discriminated union or the data-layer's typed result) — never leave loading/error/empty implicit.
Null and undefined
- Narrow at the source. If a value is optional only in a corner case, don't thread
undefinedthrough every layer — guard at the producer. - Sensible defaults for optional values. Use
?.and??at the consumer. - Lists should be filtered before being used in a map or other iteration.
- Avoid non-strict null comparisons (
X != null) whenXcan never benull— use a strict check or narrow the type. UsecheckNotNullwhere necessary. - Check actual nullability against API implementation. Find the API endpoint implementation and check if the field can actually be null.
Naming
- Names describe the entity, not the mechanism. A name must reflect what the value holds.
- Align sibling concepts: keep verb conventions consistent across a related API.
- No names that encode implementation history rather than current meaning. Suffixes like
Base,New,Old,Initialneed a real semantic distinction, otherwise drop them. - Avoid cryptic identifiers (
v,n,$n) for domain values; short names are fine only in tiny conventional contexts (loop indexi, coordinatesx/y, generic paramsT/K/V).
Code structure and organization
- Prioritize reusability over duplication. The codebase already has many utility functions — leverage them. If you introduce duplicated logic, extract it to a shared utility.
- Generic helpers do not belong in feature folders. Promote to a shared utility.
- Keep functions small and single-purpose. A 100+ line function is hard to review — split into focused named helpers, each with one responsibility and a minimal dependency surface. When necessary, cover with unit tests.
- Extract distinct complex JSX into named components. Choose same-file vs separate-file by reuse, coupling, testability, and readability.
Comments
- No comments by default. Well-named identifiers carry the
what. - Comments should be concise. Add a short, concise comment only when the
whyis non-obvious: a workaround, a hidden invariant, a subtle ordering constraint, a clever reduction. Never document the actual implementation, focus on the intent and the why.
Verify before done
- Run the project type-check when finished (see the shared TypeScript commands above).
Du fichier au premier essai
Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.
Consulter la source et ses fichiers annexesCe téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.
1. Télécharger le fichier
Télécharger SKILL.mdDepuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/typescript-javascript-with-metabase-standards-mte1lg3r/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.
Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.
mkdir -p '.skill-downloads/typescript-javascript-with-metabase-standards-mte1lg3r' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/typescript-javascript-with-metabase-standards-mte1lg3r/download' --output '.skill-downloads/typescript-javascript-with-metabase-standards-mte1lg3r/SKILL.md.part' && mv '.skill-downloads/typescript-javascript-with-metabase-standards-mte1lg3r/SKILL.md.part' '.skill-downloads/typescript-javascript-with-metabase-standards-mte1lg3r/SKILL.md'2. Vérifier les prérequis
Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.
Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.
Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.
3. Charger la skill
Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.
Claude Code
test -f '.skill-downloads/typescript-javascript-with-metabase-standards-mte1lg3r/SKILL.md' && test -s '.skill-downloads/typescript-javascript-with-metabase-standards-mte1lg3r/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/typescript-write' && cp -R '.skill-downloads/typescript-javascript-with-metabase-standards-mte1lg3r' '.claude/skills/typescript-write'OpenSkills
OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.
Installation officielle d’OpenSkillsopenskills install './.skill-downloads/typescript-javascript-with-metabase-standards-mte1lg3r'openskills read 'typescript-javascript-with-metabase-standards-mte1lg3r'La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.
Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.
openskills syncMode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.
4. Faire un premier essai
Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :
Lis .skill-downloads/typescript-javascript-with-metabase-standards-mte1lg3r/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.
Bonnes pratiques React Hook Form
Developpement
Maîtrisez React Hook Form : évitez les anti-patterns, gérez les abonnements, et traitez correctement reset, dirty state et entrées contrôlées.
Migration Emotion vers Mantine
Developpement
Migrer les styled-components Emotion vers des composants Mantine avec style props et modules CSS. Pour convertir .styled.tsx ou supprimer les imports @emotion.
Détecteur de dérive de périmètre
Developpement
Analyse les diffs git par rapport à une intention pour détecter la dérive de périmètre, fichiers non liés et PR trop larges, puis suggère de garder, diviser ou justifier.