首页 > 解决方案 > 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)
}

打字稿玩

标签: typescript

解决方案


从这个答案value在闭包中getValue(() => value)打破了control-flow-based-type-analysis

有两种解决方案:

  1. _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)
  }
}
  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)
  }
}

推荐阅读