En bref. On sait écrire un if dans le code. TypeScript permet d’en écrire un dans les types, que le compilateur résout avant l’exécution.
Le modèle en une phrase
Un type conditionnel est un if que le compilateur exécute sur des types ; infer capture un morceau du type testé.
In short. You know how to write an if in code. TypeScript lets you write one in types, which the compiler resolves before runtime.
The model in one sentence
A conditional type is an if the compiler runs on types; infer captures a piece of the tested type.
Contenu<number[]> // numberContenu<string> // stringEnTableau<string | number> // string[] | number[]
Contenu<number[]> // number— T est un tableau : la branche « alors » s'applique et infer U capture l'élément, number.T is an array: the "then" branch applies and infer U captures the element, number.Contenu<string> // string— string n'est pas un tableau : c'est la branche « sinon », et T est gardé tel quel.string is not an array: it's the "else" branch, and T is kept as is.EnTableau<string | number> // string[] | number[]— Sur une union, le conditionnel s'applique à chaque membre séparément, puis réunit les résultats.On a union, the conditional applies to each member separately, then joins the results.
La preuve, avec du code qui tourne
Extraire l’élément d’un tableau, le retour d’une fonction, et distribuer sur une union :
// Un if au niveau des types : si T est un tableau, on prend son élément.
type Contenu<T> = T extends (infer U)[] ? U : T;
type A = Contenu<number[]>; // number
type B = Contenu<string>; // string (pas un tableau : on garde T)
const a: A = 42;
const b: B = "ok";
console.log(a, b);
// @ts-expect-error A est number, pas string
const mauvais: A = "42";
// infer extrait un morceau d'un type : ici le type de retour d'une fonction.
type Retour<F> = F extends (...args: never[]) => infer R ? R : never;
function compter() { return 3; }
type R = Retour<typeof compter>; // number
const r: R = compter();
console.log(r);
// Distribution sur une union : le conditionnel s'applique à chaque membre.
type EnTableau<T> = T extends unknown ? T[] : never;
type D = EnTableau<string | number>; // string[] | number[]
const d: D = ["x"];
console.log(d);42 ok
3
[ "x" ]Le fichier compile en strict avec tsc 6. Pour un tableau de nombres, le type résultant est number ; pour une chaîne, qui n’est pas un tableau, c’est la chaîne elle-même. Affecter une chaîne à un type number est refusé, ts-expect-error le prouve. Sur string ou number, le conditionnel se distribue et donne un tableau de chaque.
Ce que l’image cache
Tout se passe à la compilation : à l’exécution, il ne reste que les valeurs. Les types conditionnels imbriqués deviennent vite illisibles, et leurs erreurs aussi. Les utilitaires ReturnType, Parameters et Awaited sont déjà des types conditionnels : mieux vaut les réutiliser que de les réécrire.
Pour aller plus loin
Le numéro ci-dessous détaille les types conditionnels, infer, la distribution sur les unions et les utilitaires qui en dépendent.
The proof, with running code
Extracting an array’s element, a function’s return, and distributing over a union:
// An if at the type level: if T is an array, take its element.
type Contenu<T> = T extends (infer U)[] ? U : T;
type A = Contenu<number[]>; // number
type B = Contenu<string>; // string (not an array: we keep T)
const a: A = 42;
const b: B = "ok";
console.log(a, b);
// @ts-expect-error A est number, pas string
const mauvais: A = "42";
// infer extracts a piece of a type: here a function's return type.
type Retour<F> = F extends (...args: never[]) => infer R ? R : never;
function compter() { return 3; }
type R = Retour<typeof compter>; // number
const r: R = compter();
console.log(r);
// Distribution over a union: the conditional applies to each member.
type EnTableau<T> = T extends unknown ? T[] : never;
type D = EnTableau<string | number>; // string[] | number[]
const d: D = ["x"];
console.log(d);42 ok
3
[ "x" ]The file compiles in strict mode with tsc 6. For an array of numbers, the resulting type is number; for a string, which isn’t an array, it’s the string itself. Assigning a string to a number type is refused, ts-expect-error proves it. On string or number, the conditional distributes and gives an array of each.
What the picture hides
Everything happens at compile time: at runtime only the values remain. Nested conditional types quickly become unreadable, and so do their errors. The ReturnType, Parameters and Awaited utilities are already conditional types: better to reuse them than rewrite them.
Go deeper
The issue below details conditional types, infer, distribution over unions and the utilities that depend on them.