You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于条件逻辑正确设置Typescript变量类型

问题根源
  • TypeScript 所有类型标注、接口定义仅在编译阶段生效,编译完成后会完全抹除所有类型信息,不会保留到 JavaScript 运行环境。你调用的typeof是原生 JavaScript 的运行时运算符,完全无法识别 TypeScript 定义的接口类型,只能返回 JS 层面的基础类型结果:
    1. 第一次打印返回undefined:你仅声明了eventProps变量没有赋初始值,运行时该变量本身就是未定义状态,和你标注的Interface1 | Interface2联合类型没有任何关联
    2. 第二次打印返回object:你赋值的两个值都是普通 JS 对象,原生 JS 中普通对象的typeof返回结果本来就是object,你用as做的只是编译期类型断言,不会对运行时的值产生任何影响
  • 你的代码还存在一个语法逻辑问题:switch的case 'event1'分支没有加break语句,就算匹配到event1,执行完对应赋值后也会继续执行default分支的逻辑,覆盖掉之前的赋值结果
可行实现方案

如果需要在运行时区分两种类型,推荐使用 TypeScript 可辨识联合类型方案:

  1. 给两个接口新增共同的字面量类型标识字段:
interface Interface1 {
  type: 'interface1'
  isCorrect: boolean
  name: string
}

interface Interface2 {
  type: 'interface2'
  isCorrect: boolean
}
  1. 修正switch逻辑赋值,不需要额外加类型断言,TypeScript 会自动匹配类型:
let eventProps: Interface1 | Interface2;

switch (event) {
  case 'event1':
    eventProps = { type: 'interface1', isCorrect: true, name: 'Mike' }
    break
  default:
    eventProps = { type: 'interface2', isCorrect: true }
}
  1. 后续需要判断类型时,直接判断标识字段即可,同时 TypeScript 会自动完成类型收窄:
if (eventProps.type === 'interface1') {
  // 此处TS会自动识别eventProps为Interface1类型,可以直接调用name属性不会报错
  console.log(eventProps.name)
}

内容的提问来源于stack exchange,提问作者Michael Gee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 02:45:05