我不明白为什么TS不能推断出这个例子中两个流的类型:
function toto(mode: boolean) {
if (mode) {
return [42]
} else {
return "mike"
}
}
const test = toto(true) // const test: number[] | "mike"
const test2 = toto(false) // const test2: number[] | "mike"
在操场上测试。
为什么自动完成只放入数组方法而不放入字符串方法(如toUpperCase)?
函数返回类型只能是一种类型,因此Typescript正在合并两个流,。。number[] | 'mike'
在很多情况下,这就是您可能想要的。
但是你可以进行函数重载,这意味着你可以对不同的输入有不同的返回类型。
例如。。
function toto(mode: true):number[];
function toto(mode: false):'mike';
function toto(mode: boolean) {
if (mode === true) {
return [42]
} else {
return "mike"
}
}
const test = toto(true)
const test2 = toto(false)
请注意,在Typscript中,文字字符串类型被缩小,因此'const a = 'hello'
不是字符串类型,而是'hello'
类型。因此,如果你想让mike
是字符串类型,你可以这样做->
function toto(mode: true):number[];
function toto(mode: false):string;
function toto(mode: boolean) {
if (mode === true) {
return [42]
} else {
return "mike" as string
}
}
const test = toto(true)
const test2 = toto(false)