Type Compatibility

Last updated

What is Type Compatibility?

TypeScript uses structural typing to determine type compatibility. This means that two types are considered compatible if they have the same structure, regardless of their names.

Here's an example of type compatibility in TypeScript:

interface Point {
  x: number;
  y: number;
}

let p1: Point = { x: 10, y: 20 };
let p2: { x: number; y: number } = p1;

console.log(p2.x); // Output: 10

In this example, p1 has the type Point, while p2 has the type { x: number; y: number }. Despite the fact that the two types have different names, they are considered compatible because they have the same structure. This means that you can assign a value of type Point to a variable of type { x: number; y: number }, as we do with p1 and p2 in this example.

Free resources to learn Type Compatibility

More in stage 4: Type Compatibility

Type Compatibility: common questions

Can I learn Type Compatibility in Hindi?

This lesson is written in English. Once you sign in, open it in the interactive course and ask the AI tutor to explain Type Compatibility in Hindi or Hinglish. The tutor answers from this lesson’s own text, so it stays on the syllabus, and it runs on your own Google, OpenAI or Anthropic key.

Is this Type Compatibility tutorial for beginners?

It is lesson 13 of 93 in the free TypeScript roadmap, in stage 4, Type Compatibility. If you are new to TypeScript, start from stage 1 and come back here in order; if you already know the earlier stages, this lesson stands on its own.

Still confused? Ask me