【发布时间】:2021-05-03 13:51:57
【问题描述】:
假设我想编写一个可以接受单个参数的函数,该参数可以是可空或不可空类型。如果参数不可为空,则返回类型也应不可为空。同样,如果参数是可为空的类型,则返回类型也应该是。
以下是我实现该功能的尝试:
type TransformKey = 'one' | 'two' | 'three'
function transform<T extends TransformKey | null>(key: T): T extends TransformKey ? string : string | null {
if (key === null)
return null as any
else
return key.toUpperCase() as any
}
函数签名似乎是正确的,因为它在调用站点上实现了所需的行为,例如:
const neverNullArg = 'two'
const neverNullResult: string = transform(neverNullArg)
const maybeNullArg: TransformKey | null = 'three'
const maybeNullResult: string | null = transform(maybeNullArg)
即返回类型确实由参数类型以正确的方式确定。
但是,我的问题在于函数实现。如果不将返回值转换为 any,则两个返回语句都会导致 TS2322 错误:Type 'null'/'string' is not assignable to type 'T extends TransformKey ? string : string | null'。所以我想知道如何在不破坏使用as any casts 或// @ts-ignore 的打字系统的情况下以满足签名的方式实现该功能。
【问题讨论】:
-
什么版本的打字稿?
-
@smac89,第 4 版
标签: typescript typescript-generics