DAY 23 OF 30
keyof and typeof
Yesterday, in one sentence
A generic constraint sets a limit on the types that can be passed to a type
parameter, written with extends. The constraint lets you use the properties
defined on it inside the function, because every allowed type must have those
properties.
Did you say:
- ✓sets a limit on the types that can be passed to a type parameter
- ✓written with `extends`
- ✓lets you use the constraint's properties inside the function
Interview question
An annotation replaces the type with the annotated one, so anything extra on the argument is lost from the return type. A type parameter keeps the exact type that was passed in.
Did you say:
- ✓an annotation replaces the type
- ✓a type parameter keeps the exact type that was passed in
- ✓it matters for the return type
The keyof operator takes an object typeObject Type and gives you
a literal unionLiteral Union of its property names.
type Hero = {
name: string;
power: string;
level: number;
};
type HeroKey = keyof Hero;
// "name" | "power" | "level"
The union is built from the type, so adding a property to Hero adds it to HeroKey
automatically.
TypeScript also has a typeof operator, which is not the JavaScript typeof from day
14 even though it is the same word. That one runs and returns a string. This one is
written in type position, reads a variable, and produces its type.
const mystique = {
name: "Raven",
level: 8,
};
type Mutant = typeof mystique;
// { name: string; level: number }
typeof mystique looks at the mystique variable above and produces the type
{ name: string; level: number }. That type is then assigned to the type alias
Mutant.
The two are often used together, to get the property names of an existing object.
const roster = {
wolverine: "Logan",
cyclops: "Scott",
};
type RosterKey = keyof typeof roster;
// "wolverine" | "cyclops"
typeof roster produces the object type, and keyof then gives its property names.
Check yourself
keyof Villain here?
type Villain = {
name: string
scheme: string
}
keyof gives a union of the property names as literal types, not the property values and not an array.
keyof and typeof do in TypeScript?keyof takes an object type and gives a union of its property names. typeof
reads a variable and produces its type. Together, keyof typeof gives the
property names of an existing object.
Did you say:
- ✓`keyof` gives a union of an object type's property names
- ✓`typeof` reads a variable and produces its type
- ✓`keyof typeof` gives the property names of an existing object