Aliases with the Structural Behavior of TypeScript
This lesson demonstrates the fundamental aspect of TypeScript to rely on objects' structures.
We'll cover the following
The structural nature of TypeScript
TypeScript is a structural language and not a nominal language. This means that TypeScript compares the structure and not the name of an object to determine if the objects are similar.
The following code has a function that takes an anonymous type that has a property name
. The example has three ways to call the function:
- interface
- type
- anonymous object
It works in all three scenarios because they have the exact shape needed.
In the following code, there is MyTypeA
that defines a schema for an object with a single member name
on line 2. On line 4, the type is the same which is also equivalent to the anonymous parameter on line 6.
Lines 10-11 define the two types and lines 12-13 invoke the function, even if it’s not the anonymous parameter. It works because they have the same structure. TypeScript is not a nominal but a structural language. Hence, on line 14, the function can also be invoked.
Get hands-on with 1400+ tech skills courses.