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

DAY 23 OF 30

keyof and typeof

Yesterday, in one sentence

What is a generic constraint, and how do you use one?

Interview question

Why would you use a generic instead of annotating the parameter with the type directly?

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

What is keyof Villain here?
type Villain = {
  name: string
  scheme: string
}
What do keyof and typeof do in TypeScript?