Use template literal types to define possible properties on typescript
I'm trying to use template literals to define an object with certain keys based on a provided string. The idea is to take a string as type argument and type the returned object to contain certain keys of certain types. However, typescript doesn't allow me to define more than one property this way. Seems that I have to create an union of all the possibilities, but that is too broad and not what I want.
Here is a non working example of what I want to achieve:
type LoadingStates<Prefix extends string> = {
[key in `${Prefix}Pending`]: boolean;
[key in `${Prefix}Error`]: string | null
}
You can use an intersection between the two mapped types. The effect will be exactly what you are looking for:
type LoadingStates<Prefix extends string> = {
[key in `${Prefix}Pending`]: boolean;
} & {
[key in `${Prefix}Error`]: string | null
}
Playground Link
You could also use the predefined type Record
instead of custom mapped types:
type LoadingStates<Prefix extends string> = Record<`${Prefix}Pending`, boolean> & Record<`${Prefix}Error`, string | null>