如何要求参数类型为联合,而不仅仅是成员?



考虑以下示例,该函数采用联合类型:

const isNull = (value: string | null) => value === null

我怎么能只允许这种用法(其中值可能为null):

const maybeNull = Math.random() < 0.5 ? 'value' : null
isNull(maybeNull)

当不允许此操作时(其中值绝对不是null):

const definitelyNotNull = 'value'
isNull(definitelyNotNull) // should error

要清楚地做到这一点,你需要某种否定类型(参见例如第4183号问题),这在TypeScript中是不可能的,但作为一个解决方案,你可以使isNull泛型,并验证null扩展参数类型:

type MaybeNull<T> = null extends T ? T : never
const isNull = <T>(value: MaybeNull<T>) => value === null

这适用于示例应用程序,尽管错误并不惊人。

const maybeNull = Math.random() < 0.5 ? 'value' : null
isNull(maybeNull) // Allowed
const definitelyNotNull = 'value'
isNull(definitelyNotNull)
// Error: Argument of type 'string' is not assignable to parameter of type 'never'.

打印稿操场

相关内容

最新更新