visit
The main aim of this piece is to grasp the workings of mapped types in TypeScript and explore various typical scenarios. I frequently come across mapped types in my work. In this guide, I'll explain how mapped types can be utilized and the assistance provided by utility types.
interface Person {
name: string;
secondName: string;
age: number;
description: string;
email: string;
id: number;
}
type PersonInputType = {
[key in keyof Person]: () => React.JSX.Element;
}
Here, keyof returns the union type of all the keys in Person interface.
What that means is, that type PersonInputType looks like this:
type PersonInputType = 'name' | 'secondName' | 'age' | 'description' | 'email';
type PersonInputType = {
[key in keyof Person]?: React.Component;
}
type PersonInputType = {
[key in keyof Pick<Person, 'name' | 'secondName'>]: () => React.JSX.Element;
}
type PersonInputType = {
[key in keyof Omit<Person, 'id'>]: () => React.JSX.Element;
}
type PersonInputType = {
[key in keyof Partial<Person>]: React.Component;
}
type PersonInputType = {
[key in keyof Required<Person>]: React.Component;
}
Let’s also consider typeof. As the name suggests typeof returns the type of an object. When it might be useful to use both keyof and typeof? For example, you have an enum, describing app states.
enum AppStates {
'READY' = 'READY',
'LOADING' = 'LOADING',
'ERROR' = 'ERROR'
}
type AppStatesInfo = {
[key in keyof typeof AppStates]: string;
}
Here, typeof here returns the typeof an object, and keyof we already discussed and now we can combine both. You can also avoid using keyof and typeof in this case and just write it shorter:
type AppStatesInfo = {
[key in AppStates]: string;
}
type AppStatesInfo = {
[key in Lowercase<AppStates>]: string;
}