Possible to extend types in Typescript?
Extend types in TypeScript with interfaces
through inheritance and with type aliases
employing intersections:
Both Extended
and ExtendedType
have an a: number
and b: string
property. Now isn't that shared quality charming?
Exploring the Extensible Features
Solution One: Using Interfaces
Interfaces
are a natural fit to merge declaration so that you can extend them using the extends
keyword:
Borrowing properties from one interface to the other was never easier. The extends
keyword facilitates this for you.
Solution Two: Using Type Aliases
Type aliases
, on the other hand, do not support declaration merging or extension. However, you can simulate the extension using intersection types, denoted by the &
operator:
Beyond Simple: Extending Complex Types
You can also extend built-in complex types. Imagine extending the Event
type like so:
Advanced Tips & Tricks
Beware of Naming Collisions
When you're borrowing properties, remember to ensure that the names are unique or share the same type. Otherwise, TypeScript will get confused and throw a type error:
The 'extends' Dilemma
The traditional extension with the extends
keyword doesn’t work with type
. Instead, consider using interfaces or intersection types.
Balancing Inline Types and Interfaces
In TypeScript, either define an interface
or use inline type according to your needs. Inline types can be handy for one-time or local type definitions, and interfaces offer flexibility for global, extendable type definitions.
Was this article helpful?