function f(x:boolean|string) { return x }
f(true) // boolean | string
为什么 typescript 不能理解返回值为 bool 值?
function f(x:boolean|string) {
return typeof x === 'boolean' ? true : 'str'
}
f(true) // boolean | string
这个也看不懂
我是否需要手动设置函数重载定义?
最佳答案
Typescript 不会根据函数中的类型保护来推断不同的返回类型。但是,您可以定义多个函数签名,让编译器知道输入参数类型和结果类型之间的联系:
function ff(x: boolean): boolean;
function ff(x: string): string;
// Implementation signature, not publicly visible
function ff(x: boolean | string): boolean | string {
return typeof x === 'boolean' ? true : 'str'
}
关于 typescript 条件返回值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48808014/