这里的value
有两种不同的类型。 一个是string
,另一个是string | string[]
function getValue(value: string | (()=>string)):void{}
function test(value: string | string[]): void{
if(value instanceof Array){
return
}
// commenting out this line resolve the issue, but I don't know why?
// TS consider `value` here as string | string[], but it should be string only
value = 'string'
// `value` here is string
getValue(value)
// but here is string | string[]
getValue(()=>value)
}
打字稿播放
从这个答案来看,闭包getValue(() => value)
中的value
打破了基于控制流的类型分析。
有两种解决方案:
- 声明一个局部变量,如
_value
string
值。
function getValue(value: string | (() => string)): void { }
function test(value: string | string[]): void {
let _value = 'string'
if (typeof value === 'string') {
getValue(value)
getValue(() => _value)
} else {
// value is string[] type here
console.log(value)
}
}
- 使用类型断言
function getValue(value: string | (() => string)): void { }
function test(value: string | string[]): void {
value = 'string'
if (typeof value === 'string') {
getValue(value)
getValue(() => value as string)
} else {
// value is string[] type here
console.log(value)
}
}