• [Typescript] 41. Medium IsUnion


    Implement a type IsUnion, which takes an input type T and returns whether T resolves to a union type.

    For example:

    type case1 = IsUnion<string>  // false
    type case2 = IsUnion<string|number>  // true
    type case3 = IsUnion<[string|number]>  // false

    Not fully understand how the solution works.

    /* _____________ Your Code Here _____________ */
    type IsUnion<T, C = T> = [T] extends [never] 
      ? false
      : T extends C 
        ? [C] extends [T] 
          ? false
          : true
        : never;
    // [T]: [void | "" | null | undefined]
    // [C]: [void] | [""] | [null] | [undefined]
    type x= IsUnion<undefined | null | void | ''> 
    
    /* _____________ Test Cases _____________ */
    import type { Equal, Expect } from '@type-challenges/utils'
    
    type cases = [
      Expect<Equal<IsUnion<string>, false>>,
      Expect<Equal<IsUnion<string | number>, true>>,
      Expect<Equal<IsUnion<'a' | 'b' | 'c' | 'd'>, true>>,
      Expect<Equal<IsUnion<undefined | null | void | ''>, true>>,
      Expect<Equal<IsUnion<{ a: string } | { a: number }>, true>>,
      Expect<Equal<IsUnion<{ a: string | number }>, false>>,
      Expect<Equal<IsUnion<[string | number]>, false>>,
      // Cases where T resolves to a non-union type.
      Expect<Equal<IsUnion<string | never>, false>>,
      Expect<Equal<IsUnion<string | unknown>, false>>,
      Expect<Equal<IsUnion<string | any>, false>>,
      Expect<Equal<IsUnion<string | 'a'>, false>>,
      Expect<Equal<IsUnion<never>, false>>,
    ]
  • 相关阅读:
    POJ 1751 Highways (kruskal)
    POJ 2031 Building a Space Station
    UVA 624
    POJ 1502 MPI Maelstrom (Dijkstra)
    POJ 3259 Wormholes(SPFA判负环)
    HZAU 1199 Little Red Riding Hood(水DP)
    HZAU 1205 Sequence Number(最大值前后缀 +双指针 + 二分)
    HZAU 1209 Deadline (hash 贪心 水题不水)
    STL完整版整理
    set集合完整版整理
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16743629.html
Copyright © 2020-2023  润新知