Want a faster signal before interviews? Take the Interview Ready Check →

DAY 24 OF 30

Indexed access types

Yesterday, in one sentence

What do keyof and typeof do in TypeScript?

Interview question

You have a roster object and want a union type of its property names. How would you write it?

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

What is Villain["scheme"] here?
type Villain = {
  name: string
  scheme: { target: string; year: number }
}
What is an indexed access type in TypeScript?