DEV Community

Jeferson Eiji
Jeferson Eiji

Posted on • Originally published at dev.to

How TypeScript Handles Type Compatibility

TypeScript uses a structural type system to check type compatibility, which means it focuses on the shape and structure of data, rather than explicit declarations. Here’s how it works:

Key Points:

  • Structural vs Nominal Typing: Unlike nominally typed languages (like Java or C#), TypeScript cares about what members an object has, not its name.

  • Compatibility Rules:

    • If an object has at least the required properties and their types, it is considered compatible.
    • Extra properties do not cause errors when assigning objects (known as ‘duck typing’).

Example: Object Compatibility

interface Point { x: number; y: number; }
let p: Point = { x: 1, y: 2 };
let q = { x: 1, y: 2, z: 3 };
p = q; // OK: q has at least the properties of Point (x, y)
Enter fullscreen mode Exit fullscreen mode

Function Compatibility Example:

let a = (x: number) => 1;
let b = (x: number, y: string) => 1;
a = b; // Error: parameter count mismatch
b = a; // OK: extra parameters in b are ignored
Enter fullscreen mode Exit fullscreen mode

Assignment Compatibility:

  • Functions: Can assign a function with fewer parameters to one expecting more (optional/extra parameters are allowed on the right side).
  • Classes: Instance members are checked, but private/protected members can restrict assignment.

Summary Table
| Feature | TypeScript compatibility rule |
|------------|--------------------------------------------------|
| Object | Shape-based (members must match) |
| Functions | Parameter count and types; extra params ignored |
| Classes | Instance members checked (private/protected count) |

Practically, TypeScript makes working with types flexible by looking at data structure rather than requiring strict inheritance or declarations.

Top comments (0)