Explain Codes LogoExplain Codes Logo

Possible to extend types in Typescript?

javascript
type-extensions
typescript-interfaces
type-aliases
Anton ShumikhinbyAnton Shumikhin·Sep 18, 2024
TLDR

Extend types in TypeScript with interfaces through inheritance and with type aliases employing intersections:

// Interface Extension: Because even interfaces have parents interface Base { a: number; } interface Extended extends Base { b: string; } // Type Alias Extension: Simpler than it looks! type BaseType = { a: number; } type ExtendedType = BaseType & { b: string; };

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:

// Interface: Your "safe word" in TypeScript interface User { id: number; } interface Author extends User { articles: string[]; } // Because authors are users too!

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:

// Our non-writers type User = { id: number; } // Writers meet the '&' operator type Author = User & { articles: string[]; } // '&' operator: The secret ingredient for authors!

Beyond Simple: Extending Complex Types

You can also extend built-in complex types. Imagine extending the Event type like so:

type UserEvent = Event & { userId: string; } // A wild userId appears!

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:

type A = { x: string; } type B = { x: number; } // Oops! Looks like you cloned 'x' type C = A & B;

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.