IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    TypeScript挑战(七) - If

    Durban发表于 2020-10-13 21:21:12
    love 0

    学习记录 - If

    题目


    实现一个utils If,它接受条件C,True返回类型T,以及False返回类型F。 C可以是True或False,而T和F可以是任何类型。

    比如

    type A = If<true, 'a', 'b'>  // expected to be 'a'
    type B = If<false, 'a', 'b'> // expected to be 'b'

    测试用例


    import { Equal, Expect } from '@type-challenges/utils'
    
    type cases = [
      Expect<Equal<If<true, 'a', 'b'>, 'a'>>,
      Expect<Equal<If<false, 'a', 2>, 2>>,
    ]
    
    // @ts-expect-error
    type error = If<null, 'a', 'b'>

    答案


    type If<C, T, F> = C extends true ? T : F

     



沪ICP备19023445号-2号
友情链接