strict et ses drapeaux : le modèle mental d'un paquet de portes qu'on ferme en TypeScript strict and its flags: the mental model of a bundle of doors you close in TypeScript

strict n'est pas un réglage mais un paquet de drapeaux : chacun ferme une porte par laquelle un bug passait en silence au runtime.strict isn't one setting but a bundle of flags: each closes a door through which a bug used to slip by silently at runtime.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
StrictStrict
PubliéPublished

En bref. « Active strict » : mais qu’active-t-on vraiment ? Un paquet de drapeaux, chacun avec son propre effet.

Le modèle en une phrase

strict est un paquet de drapeaux : chacun ferme une porte par laquelle un bug passait en silence.

In short. “Turn on strict”: but what do you actually turn on? A bundle of flags, each with its own effect.

The model in one sentence

strict is a bundle of flags: each closes a door through which a bug used to slip by silently.

r * 2 // r : number | undefined
function afficher(x) { ... } // any implicite
g(5) // x.toUpperCase is not a function
strict, un paquet de drapeauxstrict, a bundle of flagsnull et undefined ne passent plusnull et undefined ne passent plusstrictNullChecksnoImplicitAnystrictPropertyInitializationstrictFunctionTypes1 drapeau(x) activé(s) sur 41 flag(s) enabled out of 4exemple exécuté avec bun et vérifié par tscexample run with bun and checked by tsc
  1. r * 2 // r : number | undefined — strictNullChecks sort null et undefined de tous les types : multiplier une valeur peut-être absente est refusé.strictNullChecks removes null and undefined from every type: multiplying a possibly-missing value is refused.
  2. function afficher(x) { ... } // any implicite — noImplicitAny refuse un paramètre sans type : sans lui, x serait any et plus rien ne serait vérifié.noImplicitAny refuses an untyped parameter: without it, x would be any and nothing would be checked.
  3. g(5) // x.toUpperCase is not a function — strictFunctionTypes refuse un gestionnaire trop étroit : sans lui, g(5) plante au runtime. Strict, c'est le paquet de ces portes fermées.strictFunctionTypes refuses a handler that is too narrow: without it, g(5) crashes at runtime. Strict is the bundle of these closed doors.
strict n'est pas un réglage mais un paquet de drapeaux : chacun ferme une porte par laquelle un bug passait en silence. Les activer un par un, c'est refuser ces portes l'une après l'autre.strict isn't one setting but a bundle of flags: each closes a door through which a bug used to slip by silently. Enabling them one by one means closing these doors one after another.

La preuve, avec du code qui tourne

Quatre drapeaux, quatre portes fermées, chacune prouvée par une erreur attendue :

// "strict" n'est pas un réglage : c'est un paquet de drapeaux, chacun ferme une porte.

// strictNullChecks : null et undefined ne sont plus dans tous les types.
const trouver = (xs: number[]): number | undefined => xs.find((x) => x > 5);
const r = trouver([1, 2]);
// @ts-expect-error  r est peut-être undefined
const double = r * 2;
console.log("sans le drapeau, ceci planterait au runtime :", r);

// noImplicitAny : un paramètre sans type n'est plus silencieusement any.
// @ts-expect-error  le paramètre 'x' a implicitement le type 'any'
function afficher(x) { return String(x); }
console.log(afficher(7));

// strictPropertyInitialization : une propriété doit être initialisée.
class Compte {
  // @ts-expect-error  'solde' n'a pas d'initialiseur
  solde: number;
}
console.log("solde réel :", new Compte().solde);

// strictFunctionTypes : un paramètre ne peut pas être plus étroit.
type Gestionnaire = (x: string | number) => void;
// @ts-expect-error  (x: string) ne sait pas gérer un number
const g: Gestionnaire = (x: string) => console.log(x.toUpperCase());
try { g(5); } catch (e) { console.log("plantage évité par le drapeau :", (e as Error).message); }
export {};
sans le drapeau, ceci planterait au runtime : undefined
7
solde réel : undefined
plantage évité par le drapeau : x.toUpperCase is not a function. (In 'x.toUpperCase()', 'x.toUpperCase' is undefined)

Le fichier compile en strict avec tsc 6, et chaque ts-expect-error prouve qu’un drapeau refuse bien la ligne visée. L’exécution avec bun, qui ne vérifie pas les types, montre ce qui se passerait sans ces drapeaux : un undefined silencieux, un paramètre non typé, une propriété jamais initialisée, un plantage sur g(5).

Ce que l’image cache

Quatre drapeaux ne sont pas tout strict : d’autres (noImplicitThis, useUnknownInCatchVariables, alwaysStrict, strictBindCallApply) en font partie, et la liste évolue selon les versions. Strict ne vérifie pas non plus ce qui sort du système de types : un JSON reçu ou un cast reste une promesse non vérifiée.

Pour aller plus loin

Le numéro ci-dessous détaille chaque drapeau et comment migrer un projet existant vers strict pas à pas.

The proof, with running code

Four flags, four closed doors, each proven by an expected error:

// "strict" isn't a setting: it's a bundle of flags, each closes a door.

// strictNullChecks: null and undefined are no longer in every type.
const trouver = (xs: number[]): number | undefined => xs.find((x) => x > 5);
const r = trouver([1, 2]);
// @ts-expect-error  r est peut-être undefined
const double = r * 2;
console.log("without the flag, this would crash at runtime:", r);

// noImplicitAny: an untyped parameter is no longer silently any.
// @ts-expect-error  le paramètre 'x' a implicitement le type 'any'
function afficher(x) { return String(x); }
console.log(afficher(7));

// strictPropertyInitialization: a property must be initialised.
class Compte {
  // @ts-expect-error  'solde' n'a pas d'initialiseur
  solde: number;
}
console.log("actual balance:", new Compte().solde);

// strictFunctionTypes: a parameter can't be narrower.
type Gestionnaire = (x: string | number) => void;
// @ts-expect-error  (x: string) ne sait pas gérer un number
const g: Gestionnaire = (x: string) => console.log(x.toUpperCase());
try { g(5); } catch (e) { console.log("crash avoided by the flag:", (e as Error).message); }
export {};
sans le drapeau, ceci planterait au runtime : undefined
7
solde réel : undefined
plantage évité par le drapeau : x.toUpperCase is not a function. (In 'x.toUpperCase()', 'x.toUpperCase' is undefined)

The file compiles in strict mode with tsc 6, and each ts-expect-error proves a flag does refuse the targeted line. Running with bun, which doesn’t check types, shows what would happen without these flags: a silent undefined, an untyped parameter, a property never initialised, a crash on g(5).

What the picture hides

Four flags aren’t all of strict: others (noImplicitThis, useUnknownInCatchVariables, alwaysStrict, strictBindCallApply) are part of it, and the list evolves between versions. Strict also doesn’t check what comes from outside the type system: received JSON or a cast remains an unchecked promise.

Go deeper

The issue below details each flag and how to migrate an existing project to strict step by step.

Questions fréquentesFrequently asked questions

Qu'active vraiment strict ?What does strict actually enable?

Un paquet de drapeaux : strictNullChecks, noImplicitAny, strictFunctionTypes, strictPropertyInitialization et d'autres, chacun refusant une catégorie de bug.A bundle of flags: strictNullChecks, noImplicitAny, strictFunctionTypes, strictPropertyInitialization and others, each refusing a category of bug.

Que fait strictNullChecks ?What does strictNullChecks do?

Il sort null et undefined de tous les types : une valeur peut-être absente doit être vérifiée avant d'être utilisée.It removes null and undefined from every type: a possibly-missing value must be checked before use.

Pourquoi noImplicitAny compte-t-il ?Why does noImplicitAny matter?

Sans lui, un paramètre non typé devient any et le code n'est plus vérifié : le bug passe sans bruit.Without it, an untyped parameter becomes any and the code is no longer checked: the bug passes silently.

Peut-on activer les drapeaux un par un ?Can you enable flags one at a time?

Oui. On peut migrer en activant un drapeau à la fois dans le tsconfig, en corrigeant les erreurs de chacun avant de passer au suivant.Yes. You can migrate by enabling one flag at a time in the tsconfig, fixing its errors before moving to the next.

Strict garantit-il l'absence d'erreurs au runtime ?Does strict guarantee no runtime errors?

Non. Il vérifie le code, pas les données reçues : un JSON inattendu ou un cast faux passent toujours.No. It checks the code, not received data: unexpected JSON or a wrong cast still get through.

TypeScriptstricttsconfigstrictNullChecksModèle mental

← Tous les articlesAll articles