Back to Type Challenges

README.Ko

questions/01130-medium-replacekeys/README.ko.md

latest2.2 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/ko" target="_blank"></a> &nbsp;&nbsp;&nbsp;<a href="./README.md" target="_blank"></a> </p><!--info-header-end-->

Union type의 key를 대체하는 ReplaceKeys를 구현하세요. 만약 일부 유형에 해당 key가 존재하지 않는다면 대체하지 않습니다. 타입은 세 개의 인자를 받습니다.

예시:

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.ko.md" target="_blank"></a> <a href="https://tsch.js.org/1130/answer/ko" target="_blank"></a> <a href="https://tsch.js.org/1130/solutions" target="_blank"></a> <!--info-footer-end-->