Back to Type Challenges

README

questions/01130-medium-replacekeys/README.md

latest2.0 KB
Original Source
<!--info-header-start--><h1>ReplaceKeys </h1><blockquote><p>by 贱贱 <a href="https://github.com/lullabyjune" target="_blank">@lullabyjune</a></p></blockquote><p><a href="https://tsch.js.org/1130/play" target="_blank"></a> &nbsp;&nbsp;&nbsp;<a href="./README.ko.md" target="_blank"></a> </p><!--info-header-end-->

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:

ts
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
<!--info-footer-start-->

<a href="../../README.md" target="_blank"></a> <a href="https://tsch.js.org/1130/answer" target="_blank"></a> <a href="https://tsch.js.org/1130/solutions" target="_blank"></a> <!--info-footer-end-->