Bitpath

Lesson 2 · Unit 02

Keyof and Lookups

Keys as types, and the type behind a key

13 exercisesabout 3 min

What you practise

  • keyof, indexed access T[K], typeof on a value, a get(obj, key) that returns the right type

Try a question from this lesson

Pick one

Python: getattr(user, "nmae") fails only when that line runs. To reject the typo at compile time, what must the type of the key be?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

keyof

keyof T is the union of the property names of T, as literal types. For the User below it is "id" | "name".

It is computed from the type: add a field to User and the union grows with it.

Python has nothing like it. getattr(u, "nmae") passes a type checker and fails when it runs.

TypeScript
interface User {
  id: number;
  name: string;
}
type Key = keyof User; // "id" | "name"

const k: Key = "name";
// const bad: Key = "nmae"; // rejected

Concept

Indexed access

A type can be looked up the way a value can. User["id"] is the type of the id property: number. The index is itself a type.

Index with a union and you get a union back, so User[keyof User] is the type of any property value.

Nothing runs. These are questions put to the type, answered by the compiler.

TypeScript
interface User {
  id: number;
  name: string;
}
type Id = User["id"];        // number
type Val = User[keyof User];
// number | string

const v: Val = "Ada";

Concept

typeof, in a type

typeof has two lives. In an expression it is JavaScript's run-time check and gives a string such as "object". In a type position it asks the compiler for the type of a value.

That lets a value be the single source of truth: write the object once, then derive its type and its keys instead of repeating them.

TypeScript
const price = { tea: 3, cake: 5 };

type Price = typeof price;
// { tea: number; cake: number }
type Item = keyof typeof price;
// "tea" | "cake"

const i: Item = "tea";

9 more exercises in the app

  • 3× multiple choice
  • 3× fill the blanks
  • 2× type the answer
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy