Table of contents
- 1. Assignment Compatibility
- 2. Optional and Additional Properties
- 3. Disallowing Properties
- 4. Preventing Compatibility
TypeScript uses a structural type system, which means that type compatibility is based on the shape or structure of the types rather than their explicit declarations or names. This allows you to define two types with different names but identical properties, enabling interchangeability between them.
One type can be assigned to another if they share at least the same properties. The assigned type must include all the required properties of the target type, with compatible types for each property.
In the example below, an instance of
Dog can be passed to the
logCatName function since both
Dog types have the same properties:
Optional and Additional Properties
The compatibility remains intact even when optional properties (e.g.,
catTag) don’t conflict in terms of typing. Additional properties, such as
dogTag, are compatible as long as the target type doesn’t explicitly prohibit them:
To explicitly disallow a property, you can utilize the never type, which will require you to update your code:
Type compatibility applies not only to plain types but also to instances of classes. If you want to prevent type compatibility, you can use Discriminated Unions or the branded types programming pattern.