DAY 6 OF 30
Type aliases
Yesterday, in one sentence
? do to a property in an object type, and what does readonly do?? makes it an optional property, so reading it gives the type or undefined.
readonly stops the property being reassigned after the object is created.
Did you say:
- ✓`?` makes it an optional property
- ✓reading it gives the type or `undefined`
- ✓`readonly` stops the property being reassigned
Interview question
const stop from being reassigned, and what does readonly stop from being reassigned?const stops the variable being reassigned. readonly stops a property inside
the object being reassigned. They protect different things and can be used
together.
Did you say:
- ✓`const` stops the variable
- ✓`readonly` stops the property
- ✓they can be used together
A type alias gives a name to a type. You can think of it as creating a variable
for a type. You write type, the name, an =, and the type itself.
type User = {
id: number;
name: string;
};
let admin: User = { id: 1, name: "Xavier" };
let guest: User = { id: 2, name: "Beast" };
The type alias shape is defined once and referred to by name. Without a type alias you would write the whole object typeObject Type out at every place you use it. This makes type aliases reusable.
A type alias can name any type, and one alias can be used inside another.
type Id = string | number; // union type
type Scores = number[]; // array type, numbers only
type Position = [number, number]; // tuple type
type Player = {
// type alias
readonly id: Id; // readonly, cannot be reassigned
name: string;
nickname?: string; // optional property
scores: Scores;
position: Position;
};
const player: Player = {
id: "p1",
name: "Scott",
scores: [90, 85],
position: [0, 4],
};
Player uses everything from the last few days. id is a union typeUnion Type that cannot be reassigned, nickname is
an optional property, scores is an array typeArray Type,
and position is a tuple typeTuple.
Check yourself
The keyword is type, and the type goes after an =, not a colon.
A name for a type, written with the type keyword. It can be passed like a
variable wherever a type is needed, which makes the type reusable instead of
written out every time.
Did you say:
- ✓a name for a type
- ✓written with the `type` keyword
- ✓makes the type reusable