【发布时间】:2019-11-25 05:11:03
【问题描述】:
我正在尝试使函数根据参数值返回条件类型,但参数具有默认值:
function myFunc<T extends boolean>(myBoolean: T = true): T extends true
? string
: number {
return myBoolean ? 'string' : 1
}
这会引发错误Type 'true' is not assignable to type 'T'.
'true' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'boolean'.
我不明白这个错误,因为T 是一个布尔值,为什么我不能将true 分配给它?
我尝试了另一种函数重载方法:
function myFunc(myBool: true): string
function myFunc(myBool: false): number
function myFunc(myBool = true) {
return myBool ? 'string' : 1
}
myFunc()
但是现在打字稿不允许我在没有参数的情况下调用myFunc()(即使它有一个默认值)并且第一个重载有一个错误This overload signature is not compatible with its implementation signature.
是否有可能在打字稿中实现我想要实现的目标,如果儿子怎么做?
【问题讨论】:
标签: typescript