typescript 条件返回值类型?

标签 typescript conditional-statements return-value

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/

相关文章:

c - libuv:uv_tcp_connect 返回的 int 是什么?

typescript - 如何使用 Typescript 在 Redux reducer 函数内实现详尽的 switch 语句?如何处理 Redux 的内部 @@redux 操作

javascript - 在 map 中的特定索引处插入

python - 比较两个词典并打印共同点

css - iPad 条件 CSS 不工作

c - 在 c 中定义并返回一个结构

typescript - 类型检查 createAction Redux 助手

javascript - Sequelize - 如何比较日期之间的相等性

c - C 中的 For 循环及其工作原理?

Excel - 自动用其结果替换公式单元格