假设我有一个具有以下签名的函数。
function doSomething(bool = false): number | string {
if (bool) {
return '1';
} else {
return 1;
}
}
const value = doSomething();
const valueTwo = doSomething(true);
我的问题是 value
变量的 type
是 number | 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/