实现If

46 阅读1分钟

题目解析

If类型是一个自定义的工具类型,我们可以在TypeScript中模拟类似于if语句的逻辑判断,这个类型在需要根据条件动态选择类型的场景中非常有用。它接收三个参数:

  1. C:一个boolean类型,只能是truefalse
  2. T:当条件为true返回的类型。
  3. F:当条件为false返回的类型。

题解

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

type TestType = If<true, number, string> // number
type TestType2 = If<false, 'a', 'b'> // b
  • C extends boolean:确保C是一个boolean类型,即truefalse
  • C extends true ? T : F:这是条件类型的逻辑:
    • 如果Ctrue,则返回类型T
    • 如果Cfalse,则返回类型F