对于同一范围内的同一变量,TypeScript 具有不同的类型



这里的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打破了基于控制流的类型分析。

有两种解决方案:

  1. 声明一个局部变量,如_valuestring值。
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)
}
}
  1. 使用类型断言
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)
}
}

最新更新