Typage structurel : le modèle mental de la forme avant le nom en TypeScript Structural typing: the mental model of shape before name in TypeScript

En TypeScript, ce qui rend deux types compatibles n'est pas leur nom mais leur forme : tout objet qui a les bons champs passe, qu'il connaisse le type ou non.In TypeScript, what makes two types compatible isn't their name but their shape: any object with the right fields passes, whether it knows the type or not.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
Typage structurelStructural typing
PubliéPublished

En bref. On cherche un « implements » pour qu’un type soit accepté, et il n’y en a pas besoin : TypeScript ne demande pas d’où vient un objet.

Le modèle en une phrase

Deux types sont compatibles quand leurs formes s’emboîtent, pas quand leurs noms coïncident.

In short. You look for an “implements” for a type to be accepted, and none is needed: TypeScript doesn’t ask where an object comes from.

The model in one sentence

Two types are compatible when their shapes fit, not when their names match.

saluer(new Dog()) // "bonjour Rex"
saluer({ name: "Ada" }) // "bonjour Ada"
saluer({ nom: "Ada" }) // erreur tsc
La forme avant le nomShape before namea un name : acceptéa un name : acceptéNamedname: stringDogname · legs✓les formes s'emboîtentthe shapes fitexemple exécuté avec bun et vérifié par tscexample run with bun and checked by tsc
  1. saluer(new Dog()) // "bonjour Rex" — Dog n'a jamais déclaré « implements Named ». Il a un champ name de type string : la forme y est, il passe.Dog never declared "implements Named". It has a name field of type string: the shape is there, it passes.
  2. saluer({ name: "Ada" }) // "bonjour Ada" — Un simple littéral d'objet passe aussi : TypeScript ne regarde ni la classe, ni l'origine, seulement les champs.A plain object literal passes too: TypeScript looks at neither the class nor the origin, only at the fields.
  3. saluer({ nom: "Ada" }) // erreur tsc — { nom } n'a pas la forme Named : le champ name manque, tsc refuse. Le nom du type n'a jamais compté, la forme si.{ nom } doesn't have the Named shape: the name field is missing, tsc refuses. The type's name never mattered, the shape did.
Deux types sont compatibles quand leurs formes s'emboîtent, pas quand leurs noms coïncident. Pas de « implements » à déclarer : un objet qui a les bons champs passe, qu'il connaisse le type ou non.Two types are compatible when their shapes fit, not when their names match. No "implements" to declare: an object with the right fields passes, whether it knows the type or not.

La preuve, avec du code qui tourne

Une interface, deux classes sans lien et un littéral, puis une forme qui ne colle pas :

interface Named { name: string }

class Dog { name = "Rex"; legs = 4 }
class Robot { constructor(public name: string) {} }

const saluer = (n: Named) => `bonjour ${n.name}`;

console.log(saluer(new Dog()));          // aucun "implements" : la forme suffit
console.log(saluer(new Robot("R2")));    // une autre classe, même forme
console.log(saluer({ name: "Ada" }));    // un simple objet littéral

// @ts-expect-error  il manque `name` : la forme n'y est pas
saluer({ nom: "Ada" });
console.log("refusé par tsc : { nom } n'a pas la forme Named");
bonjour Rex
bonjour R2
bonjour Ada
refusé par tsc : { nom } n'a pas la forme Named

Dog, Robot et le littéral n’ont aucun lien déclaré avec Named, et tous passent : ils ont un champ name. Seul { nom } est refusé, parce que le champ attendu manque (le fichier compile en mode strict avec tsc 6, et le @ts-expect-error confirme l’erreur).

Ce que l’image cache

Le typage structurel a un revers : deux types sans rapport mais de même forme se confondent. Un identifiant d’utilisateur et un identifiant de commande, tous deux string, sont interchangeables pour le compilateur. Et ce que tsc vérifie s’efface à l’exécution : seule la forme est contrôlée, à la compilation.

Pour aller plus loin

Le numéro ci-dessous creuse la règle de compatibilité, l’inférence de forme et les cas où la forme ne suffit plus.

The proof, with running code

An interface, two unrelated classes and a literal, then a shape that doesn’t fit:

interface Named { name: string }

class Dog { name = "Rex"; legs = 4 }
class Robot { constructor(public name: string) {} }

const saluer = (n: Named) => `bonjour ${n.name}`;

console.log(saluer(new Dog()));          // no "implements": the shape is enough
console.log(saluer(new Robot("R2")));    // another class, same shape
console.log(saluer({ name: "Ada" }));    // a plain object literal

// @ts-expect-error  `name` is missing: the shape isn't there
saluer({ nom: "Ada" });
console.log("refusé par tsc : { nom } n'a pas la forme Named");
bonjour Rex
bonjour R2
bonjour Ada
refusé par tsc : { nom } n'a pas la forme Named

Dog, Robot and the literal have no declared link to Named, and all pass: they have a name field. Only { nom } is rejected, because the expected field is missing (the file compiles in strict mode with tsc 6, and the @ts-expect-error confirms the error).

What the picture hides

Structural typing has a downside: unrelated types with the same shape get mixed up. A user id and an order id, both string, are interchangeable for the compiler. And what tsc checks is erased at runtime: only the shape is verified, at compile time.

Go deeper

The issue below digs into the compatibility rule, shape inference and the cases where shape is no longer enough.

Questions fréquentesFrequently asked questions

Qu'est-ce que le typage structurel ?What is structural typing?

Un système où deux types sont compatibles si leurs formes (leurs champs) s'emboîtent, quel que soit leur nom ou leur déclaration.A system where two types are compatible if their shapes (their fields) fit, regardless of their name or declaration.

Faut-il écrire « implements » pour qu'une classe soit acceptée ?Do you need "implements" for a class to be accepted?

Non. Dog n'a jamais déclaré implements Named : il a un champ name de type string, donc il passe. implements sert à vérifier une intention, pas à être accepté.No. Dog never declared implements Named: it has a name field of type string, so it passes. implements is for checking an intent, not for being accepted.

Quelle différence avec le typage nominal ?How is it different from nominal typing?

En nominal (Java, C#), le nom du type compte : il faut déclarer la relation. En structurel, seule la forme compte, ce qui rend TypeScript souple mais plus permissif.In nominal typing (Java, C#), the type's name counts: you must declare the relationship. In structural typing only the shape counts, which makes TypeScript flexible but more permissive.

Pourquoi { nom: "Ada" } est-il refusé alors qu'il a un champ string ?Why is { nom: "Ada" } rejected when it has a string field?

Parce que la forme demandée est name, pas nom : le champ attendu manque. La compatibilité porte sur les noms de champs, pas sur le nom du type.Because the requested shape is name, not nom: the expected field is missing. Compatibility is about field names, not the type's name.

Quel est le risque du typage structurel ?What is the risk of structural typing?

Deux types sans lien peuvent avoir la même forme et être confondus : un UserId et un OrderId, tous deux string, sont interchangeables pour tsc.Two unrelated types can have the same shape and be mixed up: a UserId and an OrderId, both string, are interchangeable for tsc.

TypeScriptTypage structurelInterfacesSystème de typesModèle mental

← Tous les articlesAll articles