DAY 8 OF 30
Interfaces
Yesterday, in one sentence
A union type means the value is one of several types, written with |. An
intersection type means the value has everything from all of them at once,
written with &.
Did you say:
- ✓union: one of several types, written with `|`
- ✓intersection: everything from all of them, written with `&`
Interview question
Any type. An object type, a union type, an array type, a tuple type, an intersection type, or a primitive type.
Did you say:
- ✓any type
- ✓not just object shapes
- ✓unions, arrays, tuples, intersections
Type aliasesType Alias are not the only way to name an object typeObject Type. TypeScript has a second way of defining one, with different features, called an interface.
An interface names an object type. You write interface, the name, and the shape in
braces. There is no =.
interface User {
readonly id: number;
name: string;
nickname?: string;
}
const xavier: User = { id: 1, name: "Xavier" };
Everything inside works the same as in an object type. readonly and optional
properties behave exactly as they did on day 5.
An interface can build on another interface with the extends keyword. The new
interface gets every property from the interface it extends, plus whatever properties
it adds itself.
interface User {
readonly id: number;
name: string;
}
interface Mutant extends User {
power: string;
}
const jean: Mutant = {
id: 2,
name: "Jean",
power: "telepathy",
};
An interface can extend more than one interface at a time. You list them after the
extends keyword, separated by commas.
interface Timestamps {
readonly createdAt: string;
}
interface Student extends User, Timestamps {
year: number;
}
The extends keyword is exclusive to interfaces. A type alias cannot use it.
Interfaces and type aliases overlap, but they are not the same. The difference between them is one of the most common TypeScript interview questions, and we will add to this table as more differences come up. Here are the first two.
| Feature | Type alias | Interface |
|---|---|---|
| Types it can name | Any type: object, union, array, tuple, intersection | Object types only |
Can use the extends keyword | No ❌ | Yes ✅ |
Check yourself
An interface has no =, and it can only name an object type, not a union type.
A named object type, written with the interface keyword. You extend one with
extends, which gives the new interface every property from the one it
extends.
Did you say:
- ✓a named object type
- ✓written with the `interface` keyword
- ✓`extends` gives it every property from the one it extends