Key remapping with as in mapped types
Use as in a mapped type to derive getter names and event handlers from the keys of an object type.
You have a User type with name and age, and a second type that lists getName and getAge, kept in step by hand. When you add email to User, the getter type needs a matching edit. Derive it from User so the compiler checks the implementation for you.
Rename keys with as
In a mapped type, an as clause after in keyof T computes a new name for each key. A template literal builds the name and Capitalize upper-cases the first letter. The value type still comes from T[K].
type User = { name: string; age: number }
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
}
const user: User = { name: 'Ada', age: 36 }
const getters: Getters<User> = {
getName: () => user.name,
getAge: () => user.age,
}
console.log(getters.getName(), getters.getAge()) // prints Ada 36This compiles under --strict, and npx tsx getters.ts prints Ada 36. The object literal is the value that satisfies the derived type.
keyof T can include number and symbol keys, and Capitalize takes a string. With plain Capitalize<K>, tsc reports Type 'K' does not satisfy the constraint 'string'. string & K keeps the string keys and turns numeric and symbol keys into never, which drops them from the result.
Check keyof Getters<User> in your editor for "getName" | "getAge". Try returning a string from getAge to see TypeScript enforce the return type from User.
Derive handlers from an event map
The same shape works for handlers. The source is an object of event names to payloads, and each handler takes the payload for its event.
type Events = {
click: { x: number; y: number }
keydown: { key: string }
}
type Handlers<T> = {
[K in keyof T as `on${Capitalize<string & K>}`]: (payload: T[K]) => void
}
const handlers: Handlers<Events> = {
onClick: ({ x, y }) => console.log(`click at ${x},${y}`),
onKeydown: ({ key }) => console.log(`key ${key}`),
}
handlers.onClick({ x: 10, y: 20 }) // prints click at 10,20
handlers.onKeydown({ key: 'Enter' }) // prints key EnterThe destructured x, y and key need no annotations, because each handler's parameter type is its event's payload.
I broke it two ways. Calling key.toFixed() inside onKeydown gave Property 'toFixed' does not exist on type 'string', so the payload type reached the parameter. Adding an onScroll handler gave 'onScroll' does not exist in type 'Handlers<Events>', so a handler needs an event in Events first.