Implement `MapTypes<T, R>` which will transform types in object T to different types defined by type R which has the following structure Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement MapTypes<T, R>, a utility type that transforms the value types of an object T according to mapping rules defined by R, which specifies mapFrom and mapTo pairs.
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 key which value is string
mapTo: number; // will be transformed for number
}type StringToNumber = { mapFrom: string; mapTo: number;}
MapTypes<{iWillBeANumberOneDay: string}, StringToNumber> // gives { iWillBeANumberOneDay: number; }Be aware that user can provide a union of types:
type StringToNumber = { mapFrom: string; mapTo: number;}
type StringToDate = { mapFrom: string; mapTo: Date;}
MapTypes<{iWillBeNumberOrDate: string}, StringToDate | StringToNumber> // gives { iWillBeNumberOrDate: number | Date; }If the type doesn't exist in our map, leave it as it was:
type StringToNumber = { mapFrom: string; mapTo: number;}
MapTypes<{iWillBeANumberOneDay: string, iWillStayTheSame: Function}, StringToNumber> // // gives { iWillBeANumberOneDay: number, iWillStayTheSame: Function }Change the following code to make the test cases pass (no type check errors).
type MapTypes<T, R extends { mapFrom: any; mapTo: any }> = {
[K in keyof T]: T[K] extends R['mapFrom']
? R extends { mapFrom: T[K]; mapTo: infer To }
? To
: never
: T[K];
};How it works:
K in the object T using a mapped typeT[K] extends any of the mapFrom types in the union RR to only the union members whose mapFrom matches T[K] exactly, using R extends { mapFrom: T[K]; mapTo: infer To } -- this distributes over the union to collect all matching mapTo typesTo types are automatically unioned together when multiple mapping rules match the same source type, which handles the case where R is a union like { mapFrom: string; mapTo: Date } | { mapFrom: string; mapTo: null }T[K] does not match any mapFrom in R, the original type is preserved unchangedThis challenge helps you understand distributive conditional types within mapped types, and how to apply these concepts in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount