Working with Structural Subtyping in TypeScript

24 Jun 2023 Balmiki Mandal 0 Typescript

Working with Structural Subtyping in TypeScript

Structural subtyping is a powerful tool in TypeScript. It allows developers to establish relationships between two objects without any explicit references between them. By utilizing structural subtyping, developers can create more type-safe code and increase the flexibility of their programs.

In TypeScript, structural subtyping works by defining the members of an object that must match for the types to be considered compatible. When two objects are compared for structural subtyping, TypeScript looks for commonality between them. If they have the same number and type of members, and the members are equivalent, the objects are structurally equivalent and will be resolved as compatible.

A key concept in structural subtyping is that it does not consider the names of the members when making the comparison. The names of the members do not need to match, only the types, for the objects to be considered compatible.

To demonstrate how structural subtyping works in TypeScript, let's take a look at this simple example:


interface A {
  x: number;
  y: string;
}

interface B {
  foo: number;
  bar: string;
}

let a: A = { x: 1, y: 'Hello' };
let b: B = { foo: 2, bar: 'World' };

let c: A = b; // OK

In this example, we have two interfaces, A and B, that have different member names but the same types. We then declare two objects, a and b, that conform to these interfaces. Event though the names of the members are different, TypeScript considers them structurally equivalent since they have the same types. Therefore, the assignment c = b is allowed.

Structural subtyping is a powerful tool in TypeScript that helps developers create more type-safe code. By establishing relationships between different objects, even if they don't explicitly refer to one another, developers can ensure that their code is properly typed and their programs are more flexible.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.