从“控制流”推导并收窄(Control Flow + Narrowing)

0 阅读1分钟

当类型是联合类型时,TS 会根据你的判断缩小范围:

function print(x: string | number) {

  if (typeof x === 'string') {

    x.toUpperCase() // x: string

  } else {

    x.toFixed(2)    // x: number

  }

}

常见收窄手段:

  • typeof、判空、in、字面量比较、instanceof、自定义 type guard。