MapTypes
Less than 1 minuteTC-Medium
MapTypes
Problem
Implement MapTypes<T, R> which will transform types in object T to different types defined by type R which has the following structure:
type StringToNumber = {
mapFrom: string // value of type string
mapTo: number // will be transformed to type number
}type SetMixed = MapTypes<{isFun: boolean, year: string}, {mapFrom: boolean; mapTo: string} | {mapFrom: string; mapTo: boolean}>
// {isFun: string, year: boolean}Solution
Approach: Mapped Type with Union Lookup
For each property, find the matching mapFrom in R and use the corresponding mapTo.
type MapTypes<T, R extends { mapFrom: unknown; mapTo: unknown }> = {
[K in keyof T]: T[K] extends R['mapFrom']
? R extends { mapFrom: T[K]; mapTo: infer To }
? To
: never
: T[K]
}How it works:
- For each key
K, check ifT[K]is a validmapFromvalue. - If so, filter
Rto the specific variant wheremapFrommatchesT[K], and extractmapTo. - If no match, keep the original type
T[K]. - When
Ris a union,R extends { mapFrom: T[K] }distributes and collects all matchingmapTotypes.
Key Takeaways
- Filtering a union with
R extends { mapFrom: T[K] }distributes over the union and keeps only matching variants. - This is the type-level equivalent of
findon an array of mapping rules. - When multiple rules match, the result is the union of all
mapTotypes.
