typescript · level 3 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Look up a property's type the way you look up its value.
You read a value with rex["age"]. You can read a type the same way. Pet["age"] is an : the type of the age property of Pet, here number. If Pet changes, every lookup follows.
With a generic key it becomes exact. A function that takes key: K can return T[K], so get(rex, "age") gives a number and get(rex, "name") gives a string. For a list, (typeof sizes)[number] means the type of any item in it.
interface Pet {
name: string;
age: number;
}
type Age = Pet["age"];
function get<T, K extends keyof T>(item: T, key: K): T[K] {
return item[key];
}
const rex: Pet = { name: "Rex", age: 4 };
const years: Age = get(rex, "age");
const sizes = ["S", "M", "L"] as const;
const mine: (typeof sizes)[number] = "M";
console.log(years + 1, mine); Inside an indexed access type, number means any index, so you get every item's type at once.
guess first
Get a film's year as a title. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
interface Film {
title: string;
year: number;
}
function get<T, K extends keyof T>(item: T, key: K): T[K] {
return item[key];
}
const film: Film = { title: "Paddington", year: 2014 };
const title: string = get(film, "year");
console.log(title);
your turn
Your turn. Order a dish from the menu.
Write the indexed access that means any item of menu, then order one of the three dishes.
fix it
The delivery cities will not load. Fix the lookup.
- Read the error:
TS2339saysOrderhas no property calledcity. citylives insidecustomer, one level down. Look it up in two steps.- Change line 5 to
type City = Order["customer"]["city"];then run.
nailed it
you can look types up by name now. :D
Pet["age"]is the type of theageproperty.- Return
T[K]so each key gets its own exact type. (typeof list)[number]is the type of any item in the list.
new words in your collection
- indexed access type
This lesson isn’t saved. A free account remembers every lesson you finish.