javascript - Typescript 根据 if 语句自动判断类型是什么

标签 javascript typescript

假设我有一个具有以下签名的函数。

function doSomething(bool = false): number | string {
    if (bool) {
        return '1';
    } else {
        return 1;
   }
}

const value = doSomething();

const valueTwo = doSomething(true);

我的问题是 value 变量的 typenumber | string 在这两种情况下。我如何告诉 typescript 根据 if block 返回正确的类型而不做类似的事情:

const value = doSomething() as number;

const valueTwo = doSomething(true) as string;

最佳答案

一个函数可以有多个签名,如果返回类型依赖于原始值,则可以使用文字类型来区分。在你的情况下你可以写:

// Public sigantures 
function doSomething(bool?: false): number // With false constant
function doSomething(bool: true): string // With true constant or missing
function doSomething(bool?: boolean): number | string // With unknown bool value 
// Implementation siganture
function doSomething(bool: boolean = false): number | string {
    if (bool) {
        return '1';
    } else {
        return 1;
    }
}
var s = doSomething(true) // s is string
var n2 = doSomething() // n2 is number
var n3 = doSomething(false) // n3 is number
declare var b: boolean;
var ns4 = doSomething(b) // ns4 is string | number because it can't be determined at compile time

关于javascript - Typescript 根据 if 语句自动判断类型是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48583322/

相关文章:

javascript - react : setInterval Not working after one interval

node.js - 从 Koa Controller 操作返回 promise 错误

javascript - 如何将特定国家/地区的 map 加载到 OpenStreetMap 中?

javascript - RequireJS 和 CommonJS 的区别

javascript - 在网站中自定义 Braintree Drop-in UI

node.js - 创建包含 TypeScript 中所有导出的模块

javascript - 大括号上的 JS 正则表达式

JavaScript 替换是将所有空格替换为非空格

typescript - 类型化对象联合的详尽映射

string - 奇怪的 typescript 字符串枚举无法从字符串解析