【问题标题】:TypeScript conditional return value type?TypeScript 条件返回值类型?
【发布时间】: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


【解决方案1】:

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'
}

【讨论】:

  • 实际上,早在操场上,打字稿就是 capable of this 至少早在 2019 年。唯一需要注意的是它没有智能在里面为你打字该函数(我认为这是一个错误),但任何正确调用它的东西都有正确的类型。
  • @Hashbrown 您正在使用条件类型。 1. 这个答案早于条件类型。 2.我支持过载解决方案。我喜欢条件类型,但在任​​何地方都使用它们是多余的。
  • 啊,是的,我 3.33 与游乐场一样远,所以我无法检查问题何时得到回答。对于这种情况,重载是完美的,这就是我没有回答的原因,'只是想确保任何其他出于更复杂原因而来的读者看到原始问题在 TS 中是可行的?
  • 在ES6中,是否所有的签名都需要通过export导出?
  • @kungfooman 是的,否则你会得到Overload signatures must all be exported or non-exported. ts(2383)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 2019-10-13
  • 2020-10-27
  • 1970-01-01
  • 2019-04-09
  • 2021-10-17
  • 2018-12-28
相关资源
最近更新 更多