Lesson 2 · Unit 02
Keyof and Lookups
Keys as types, and the type behind a key
What you practise
keyof, indexed accessT[K],typeofon a value, aget(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?
Correct answer
One of that object's own property names
Why
string lets every typo through, since a typo is a string too. The key has to be a union of the object's own property names, such as "id" | "name", and it has to be computed from the object type or it goes stale. That operator is keyof.
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.
interface User {
id: number;
name: string;
}
type Key = keyof User; // "id" | "name"
const k: Key = "name";
// const bad: Key = "nmae"; // rejectedConcept
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.
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.
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.