Skip to content

If

自 1.1.0 起

类型级别的 if-then-else。

签名

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

参数

参数描述
C条件(布尔类型)
T条件为真时返回的类型
F条件为假时返回的类型

示例

基本用法

typescript
import type { If } from 'uni-types'

type A = If<true, string, number>    // string
type B = If<false, string, number>   // number

与类型谓词

typescript
import type { If, IsAny } from 'uni-types'

type SafeResult<T> = If<IsAny<T>, never, T>

type A = SafeResult<string>  // string
type B = SafeResult<any>     // never

条件逻辑

typescript
import type { If, And, Or } from 'uni-types'

type Result<A extends boolean, B extends boolean> = If<
  Or<A, B>,
  '至少有一个为真',
  '两个都为假'
>

相关

  • Not - 逻辑非
  • And - 逻辑与
  • Or - 逻辑或

基于 MIT 许可发布