DAY 24 OF 30
Indexed access types
Yesterday, in one sentence
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
Interview question
roster object and want a union type of its property names. How would you write it?keyof typeof roster. typeof roster produces the object type from the variable,
and keyof gives a union of its property names.
Did you say:
- ✓`keyof typeof roster`
- ✓`typeof` on the variable first
- ✓`keyof` then gives the property names
An indexed access type looks up the type of one property on an object type. You write it in square brackets, the same way you would read the property from an object.
type Hero = {
name: string;
level: number;
};
type HeroName = Hero["name"];
// string
Hero["name"] looks up the property called name and gives back its type, which is
string.
The property name in the brackets is written as a literal typeLiteral Type, so you cannot use a variable there.
type Hero = {
name: string;
level: number;
};
const key = "name";
type Wrong = Hero[key];
// ❌ 'key' refers to a value, but is being used as a type
You can pass a union typeUnion Type in the brackets, which gives you a union of those property types.
type HeroValue = Hero["name" | "level"];
// string | number
Combined with keyofkeyof, that gives you the type of every property in the object type.
type AnyHeroValue = Hero[keyof Hero];
// string | number
It works on an array typeArray Type too. Arrays are indexed by
numbers, so putting number in the brackets gives you the element type.
type Roster = string[];
type Member = Roster[number];
// string
On a tupleTuple each position has its own type, so you can look one
up by its index, and number gives a union of all of them.
type Entry = [string, number];
type First = Entry[0]; // string
type Either = Entry[number]; // string | number
Check yourself
Villain["scheme"] here?
type Villain = {
name: string
scheme: { target: string; year: number }
}
An indexed access type gives the type of that property, which here is the object type on scheme.
Looking up the type of a property on an object type, written in square brackets
like Hero["name"]. The property name in the brackets is written as a type, and
passing a union of names gives a union of those property types.
Did you say:
- ✓looks up the type of a property on an object type
- ✓written in square brackets like `Hero["name"]`
- ✓a union of names gives a union of those property types