Implement a type ReplaceKeys, that replace keys in union types, if some type has not this key, just skip replacing, Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a ReplaceKeys type that replaces specified keys across union types with new types from a lookup object, setting keys to never when the replacement type is not provided.
Implement a type ReplaceKeys, that replace keys in union types, if some type has not this key, just skip replacing, A type takes three arguments.
For example:
type NodeA = {
type: "A"
name: string
flag: number
}
type NodeB = {
type: "B"
id: number
flag: number
}
type NodeC = {
type: "C"
name: string
flag: number
}
type Nodes = NodeA | NodeB | NodeC
type ReplacedNodes = ReplaceKeys<
Nodes,
"name" | "flag",
{ name: number; flag: string }
> // {type: 'A', name: number, flag: string} | {type: 'B', id: number, flag: string} | {type: 'C', name: number, flag: string} // would replace name from string to number, replace flag from number to string.
type ReplacedNotExistKeys = ReplaceKeys<Nodes, "name", { aa: number }> // {type: 'A', name: never, flag: number} | NodeB | {type: 'C', name: never, flag: number} // would replace name to neverChange the following code to make the test cases pass (no type check errors).
type ReplaceKeys<U, T, Y> = U extends U
? {
[K in keyof U]: K extends T
? K extends keyof Y
? Y[K]
: never
: U[K]
}
: neverHow it works:
U extends U is a distributive conditional type pattern that ensures the type distributes over union members. Each member of the union U is processed individually.K.K extends T checks whether the current key is one of the keys we want to replace.K extends keyof Y checks whether the replacement lookup object Y actually has a replacement type for this key. If so, we use Y[K] as the new type.Y does not contain a matching key, the property type becomes never.T, we keep the original type U[K].This challenge helps you understand distributive conditional types and mapped type transformations over union 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