[Typescript] 130. Hard - Replace Union

Given an union of types and array of type pairs to replace ([[string, number], [Date, null]]), return a new union replaced with the type pairs.

 

/* _____________ Your Code Here _____________ */

type UnionReplace<T, U extends [any, any][]> = U extends [infer F, ...infer RT extends [any, any][]]
  ? F extends [infer ToBeReplaced, infer Replacer]
    ? UnionReplace<Exclude<T, ToBeReplaced> | Replacer, RT>
    : UnionReplace<T, RT>
  : T


/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  // string -> null
  Expect<Equal<UnionReplace<number | string, [[string, null]]>, number | null>>,

  // Date -> string; Function -> undefined
  Expect<Equal<UnionReplace<Function | Date | object, [[Date, string], [Function, undefined]]>, undefined | string | object>>,
]

 

posted @ 2022-12-07 20:12  Zhentiw  阅读(15)  评论(0编辑  收藏  举报