Back to articles
How TypeScript Handles Type Compatibility

How TypeScript Handles Type Compatibility

via Dev.to WebdevJeferson Eiji

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) 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 Assignment Compatibility: Functions: Can assign

Continue reading on Dev.to Webdev

Opens in a new tab

Read Full Article
2 views

Related Articles