DAY 10 OF 30
Structural typing
Yesterday, in one sentence
Declaring the same interface name more than once, and TypeScript combining them into a single interface with all the properties. Type aliases cannot do this.
Did you say:
- ✓the same interface name declared more than once
- ✓TypeScript combines them into one
- ✓type aliases cannot do this
Interview question
A type alias can name any type, an interface can only name an object type. An
interface can be extended with extends and can be reopened and merged, a type
alias cannot do either. Most teams pick one and stay consistent.
Did you say:
- ✓aliases can name any type
- ✓interfaces name object types only
- ✓`extends` is interface only
- ✓interfaces can be merged, aliases are closed
TypeScript decides whether two types are compatible by comparing their shape, not their name. This is called structural typing, and it is sometimes called duck typing: if it looks like a duck, it is a duck.
interface Mutant {
id: number;
power: string;
}
type Magic = {
id: number;
power: string;
};
const juggernaut: Magic = { id: 1, power: "unstoppable" };
const mutant: Mutant = juggernaut; // ok, the shapes match
Mutant was declared as an interfaceInterface and Magic as a type aliasType Alias, but they have the same properties with
the same types, so a value of one is assignable to the other.
Check yourself
interface Peter {
name: string
city: string
}
type Miles = {
name: string
city: string
}
TypeScript compares shape, not name. Peter typed as a SpiderMan and Miles typed as a Webslinger are assignable to each other, because both types ask for the same properties.
TypeScript compares types by their shape rather than their name. If a value has the properties a type requires, it is compatible with that type.
Did you say:
- ✓types are compared by shape, not name
- ✓having the required properties is enough