Sub topic 7
Building on existing shapes with extends
This chapter assumes you can write basic interfaces and type aliases, and that you know optional and readonly properties. You should also understand structural typing: a value matches a type when it has the required members, whatever its declared name.
What extends does
extends creates a new interface that includes every member of an existing one, then adds more. It avoids copying property lists, and it records an "is a kind of" relationship the compiler checks.
interface Named {
name: string;
}
interface Employee extends Named {
employeeId: number;
}
const grace: Employee = { name: "Grace", employeeId: 7 };Employee now requires both name and employeeId. If someone adds a property to Named, Employee picks it up automatically.
Because typing is structural, a value of type Employee can be passed anywhere a Named is expected. The reverse fails, because a plain Named lacks employeeId.
interface Named {
name: string;
}
interface Employee extends Named {
employeeId: number;
}
function greet(who: Named): string {
return `Hello, ${who.name}`;
}
const grace: Employee = { name: "Grace", employeeId: 7 };
console.log(greet(grace)); // Hello, Grace
const anon: Named = { name: "Anon" };
// const asEmployee: Employee = anon; // error: Property 'employeeId' is missingExtending several interfaces
An interface can list more than one base, separated by commas. The result has the members of all of them.
interface Named {
name: string;
}
interface Timestamps {
createdAt: Date;
updatedAt: Date;
}
interface Employee extends Named, Timestamps {
employeeId: number;
}
const e: Employee = {
name: "Grace",
employeeId: 7,
createdAt: new Date(),
updatedAt: new Date(),
};Small, focused bases such as Named and Timestamps can be mixed into many interfaces. This is the usual reason to use multiple extension.
If two bases declare the same property with identical types, there is no problem. If the types differ, the compiler rejects the declaration:
interface A {
id: string;
}
interface B {
id: number;
}
// error: Interface 'C' cannot simultaneously extend types 'A' and 'B'.
// interface C extends A, B {}The error appears at the declaration, which is where you want to learn about it.
Overriding members
A derived interface may redeclare a property from its base, but the new type must be assignable to the base type. In practice you can narrow a property and you cannot widen or change it.
interface Shape {
kind: string;
label?: string;
}
interface Circle extends Shape {
kind: "circle"; // narrower than string: allowed
label: string; // optional made required: allowed
radius: number;
}
const c: Circle = { kind: "circle", label: "unit", radius: 1 };Narrowing kind to a literal type is a common pattern. It gives each derived interface a distinct tag, and later you can combine those interfaces into a discriminated union.
Changing a property to an incompatible type is an error:
interface Named {
name: string;
}
// error: Interface 'Bad' incorrectly extends interface 'Named'.
// Types of property 'name' are incompatible.
// interface Bad extends Named {
// name: number;
// }The rule exists so that every Bad could still be used as a Named. If name were a number, code that calls .toUpperCase() on a Named would break at runtime.
Extending type aliases
An interface can extend a type alias, as long as the alias names an object type (or an intersection of object types) whose members are known at compile time.
type Timestamps = { createdAt: Date; updatedAt: Date };
interface Post extends Timestamps {
title: string;
}
const post: Post = {
title: "Hello",
createdAt: new Date(),
updatedAt: new Date(),
};An alias that names a union cannot be extended, because a union has no single fixed set of members.
type Result =
| { ok: true; value: string }
| { ok: false; error: Error };
// error: An interface can only extend an object type or intersection
// of object types with statically known members.
// interface Wrapped extends Result {}The relationship works in the other direction too. A type alias can build on an interface with an intersection, which the next section compares.
Generic bases
A base can take type arguments. The derived interface supplies them, or passes its own type parameters through.
interface ApiResponse<T> {
data: T;
status: number;
}
interface PagedResponse<T> extends ApiResponse<T[]> {
page: number;
totalPages: number;
}
const users: PagedResponse<string> = {
data: ["ada", "grace"],
status: 200,
page: 1,
totalPages: 3,
};Here PagedResponse<string> has data: string[], because the base was instantiated with T[]. You can also fix the argument: interface UserResponse extends ApiResponse<User> {}.
extends versus intersection
The type alias counterpart of extends is the intersection operator &. For ordinary object shapes the results are equivalent.
interface Named {
name: string;
}
interface EmployeeA extends Named {
employeeId: number;
}
type EmployeeB = Named & { employeeId: number };
const a: EmployeeA = { name: "Grace", employeeId: 7 };
const b: EmployeeB = { name: "Grace", employeeId: 7 };The differences show up when members conflict, and in how errors read.
| Aspect | `interface X extends Y` | `type X = Y & Z` |
|---|---|---|
| Conflicting property types | Compile error at the declaration | No error at the declaration. The property becomes `never` (for primitives) |
| Overriding a property | Allowed if the new type is assignable to the old one | Not an override: both types apply, so the property type is the intersection of the two |
| Can combine with a union alias | No | Yes, though the result distributes over the union |
| Error messages and tooling | Shows the interface name | Often shows the expanded structure |
| Extensible later by merging | Yes, interfaces can merge | No |
Here is the conflict case in code:
type A = { id: string };
type B = { id: number };
type C = A & B; // no error here
// C["id"] is string & number, which is never.
// A value of type C cannot be created:
// const c: C = { id: "x" }; // error: Type 'string' is not assignable to type 'never'.The intersection compiles, but the type is unusable. The mistake is only found where you try to create a value. With extends, you find it immediately. This is the strongest practical argument for extends when you are building a hierarchy of related object types.
The error-message and performance differences are smaller. The TypeScript team has noted that interface relationships are cached by name, while intersections are re-evaluated structurally. This rarely matters for small types, but it can affect compile time in very large codebases.
Common mistakes
- Treating extension as copying. The derived interface stays linked to the base. Adding a required member to the base breaks every value that was typed as the derived interface and lacks it. This is useful when you want the change to be enforced, and surprising when you did not expect it.
- Deep hierarchies. Chains of five or six interfaces make it hard to see what a type contains. Prefer a few small bases combined with multiple
extends. - Expecting excess property checks on variables. A derived interface does not make a looser check. Fresh object literals are still checked for extra properties, and variables are not.
- Extending a union alias. As shown above, this is rejected. Use an intersection, or restructure so the union members each extend a common base.
Exercise
Given interface A { id: string } and interface B { id: number }, what happens with interface C extends A, B {} and with type D = A & B? Which one tells you about the problem earlier, and why?
Show answer
interface C extends A, B {} is a compile error: Interface 'C' cannot simultaneously extend types 'A' and 'B'. type D = A & B compiles, but D["id"] is string & number, which is never, so you cannot create a value of type D. The interface reports the problem at the declaration. The intersection only reports it when you try to build a value or use the property.
Exercise
You have interface Shape { kind: string }. Write a Square interface that extends Shape, fixes kind to the literal "square", and adds size: number. Then explain why interface Odd extends Shape { kind: number } fails.
Show answer
interface Square extends Shape { kind: "square"; size: number }. The literal "square" is assignable to string, so the override is allowed. interface Odd extends Shape { kind: number } fails because number is not assignable to string. An Odd would not be usable wherever a Shape is expected, so the compiler reports that Odd incorrectly extends Shape.