【发布时间】:2021-03-01 16:03:34
【问题描述】:
function f(x:boolean|string) { return x }
f(true) // boolean | string
为什么 typescript 不能理解返回值是布尔值?
function f(x:boolean|string) {
return typeof x === 'boolean' ? true : 'str'
}
f(true) // boolean | string
它也无法理解。
是否需要手动设置函数重载定义?
【问题讨论】:
-
因为不是如果 typeof x 等于 'boolean' 则返回布尔值,否则返回字符串。这就是三元运算符的工作原理。
-
你还想实现什么?目标是什么?
-
function f(x :boolean|string) :typeof x extends boolean ? boolean : string {
标签: typescript conditional-statements return-value