#1130Medium

ReplaceKeys

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.

Challenge Instructions: ReplaceKeys

Medium

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 never

Change the following code to make the test cases pass (no type check errors).

Loading...

Detailed Explanation

type ReplaceKeys<U, T, Y> = U extends U
  ? {
      [K in keyof U]: K extends T
        ? K extends keyof Y
          ? Y[K]
          : never
        : U[K]
    }
  : never

How it works:

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.

Share this challenge

Learn the Concepts

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount