typescript · level 3 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
lists every key of a type as a union.
keyof Pet reads the keys of the type Pet and makes a union of literal types. If Pet has name and age, then keyof Pet is "name" | "age". For a value, add a type query first: keyof typeof settings.
It shines in functions. K extends keyof T means K must be one of the real keys of T. A misspelt key, like "nmae", is caught by the checker instead of quietly giving undefined at runtime.
interface Pet {
name: string;
age: number;
}
type PetKey = keyof Pet;
const field: PetKey = "age";
function show<T, K extends keyof T>(item: T, key: K): void {
console.log(`${String(key)}: ${item[key]}`);
}
const rex: Pet = { name: "Rex", age: 4 };
show(rex, field);
show(rex, "name"); String(key) is needed because keys can also be numbers or symbols, a rarer kind of key.
guess first
Ask for a subject that is not there. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const scores = { maths: 8, art: 9, music: 6 };
function getScore(subject: keyof typeof scores): number {
return scores[subject];
}
console.log(getScore("art"));
console.log(getScore("science"));
your turn
Your turn. Check the fruit stall.
Make fruit accept only the keys of stock, then ask about one fruit from the stall.
fix it
The pet counter will not run. Fix the key.
- Read the error:
Kcannot be used to look insideT. Why might that be? Kcould be any type at all, not only a key ofT. It needs a constraint.- On line 1, change
KtoK extends keyof T, then run.
nailed it
your functions only accept real keys now. :D
keyof Petis the union ofPet's keys.keyof typeof valuegets the keys of a value.K extends keyof Tcatches misspelt keys before the code runs.
new words in your collection
- keyof
This lesson isn’t saved. A free account remembers every lesson you finish.