
This short and straightforward article shows you a couple of different ways to extend a type in TypeScript. Without any further ado, let’s see the code.
Using the “extends” keyword
Example:
type TypeOne = {
a: string;
b: number;
};
type TypeTwo = {
c: string;
d: string;
};
// extend TypeOne
interface InterfaceOne extends TypeOne {
e: string;
f: number;
}
const x: InterfaceOne = {
a: 'KindaCode.com',
b: 1,
e: 'e',
f: 2,
};
// you can also extend multiple types at once
interface InterfaceTwo extends TypeOne, TypeTwo {
g: string;
}
const y: InterfaceTwo = {
a: 'a',
b: 1,
c: 'c',
d: 'd',
g: 'Welcome to KindaCode.com',
};
Using the “&” operator
Example:
type TypeA = {
a1: string;
a2: string;
}
type TypeB = {
b1: string;
b2: number;
}
// Extend TypeA
type TypeAExtended = TypeA & {
a3: string;
a4: number;
}
// Extend both TypeA and TypeB at the same time
type TypeC = TypeA & TypeB & {
c1: string;
c2: number;
c3: boolean;
}
That’s it. Further reading:
- React + TypeScript: Using setTimeout() with Hooks
- VS Code & Javascript/TypeScript: Place Curly Braces on New Line
- TypeScript: Object with Optional Properties
- React + TypeScript: Multiple Select example
- React + TypeScript: onMouseOver & onMouseOut events
- React + TypeScript: setInterval() example (with hooks)
You can also check out our TypeScript category page for the latest tutorials and examples.