typescript · level 3 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Rename keys inside a mapped type with as.
Inside a mapped type, as gives each new property a different name. This is . Below, as with the pattern get${Capitalize<K & string>} turns the key name into getName, so a whole set of method names grows from one type.
One snag: keys can be numbers as well as strings, and Capitalize only takes strings. K & string keeps only the string part. The & makes an : a value must fit both sides at once. Remap a key to never and it disappears.
type Getters<T> = {
[K in keyof T as `get${Capitalize<K & string>}`]: () => T[K];
};
interface Pet {
name: string;
age: number;
}
const rex: Getters<Pet> = {
getName: () => "Rex",
getAge: () => 4,
};
console.log(rex.getName(), rex.getAge() + 1); () => T[K] is a function type for a function that takes nothing and hands back that property's type.
guess first
Flag a door as open. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
type Flags<T> = {
[K in keyof T as `is${Capitalize<K & string>}`]: boolean;
};
interface Door {
open: string;
locked: string;
}
const door: Flags<Door> = { isOpen: true, isLocked: false, open: true };
console.log(door.isOpen);
your turn
Your turn. Hide the password.
Make the password key disappear by remapping it to the type with no values. Then fill in a name.
fix it
The volume setter will not build. Fix it.
- Read the error:
TS2344saysKdoes not satisfy the constraintstring. Capitalizeonly takes strings, but a key ofTmight be a number.- On line 2, write
Capitalize<K & string>to keep only the string keys.
nailed it
you can rename keys as you map them. :D
asinside a mapped type renames each key.K & stringkeeps only string keys for helpers likeCapitalize.- Remap a key to
neverand it disappears.
new words in your collection
- key remapping
- intersection type
This lesson isn’t saved. A free account remembers every lesson you finish.