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

TypeScript严格模式下枚举为何可能为undefined?如何修复?

TypeScript严格模式下Partial类型导致的类型报错修复

问题原因

确实是Partial<Player>导致的报错。Partial<T>工具类型会将原类型T的所有属性转换为可选属性,所以player.state的类型变成了State | undefined。而数组的includes()方法要求传入的参数类型必须和数组元素类型(这里是State)完全匹配,undefined不满足这个要求,因此触发ts(2345)类型错误。

修复方案

以下是几种可行的修复方式,可根据实际业务场景选择:

  • 非空断言(需确保运行时存在值)
    如果你能保证player.state在运行时一定有值,可以用非空断言!告诉TypeScript忽略undefined的情况:

    const isOK = [State.Completed, State.Discontinued].includes(player.state!);
    
  • 类型收窄判断
    先判断player.state是否存在,TypeScript会自动收窄类型,此时调用includes()就不会报错:

    const isOK = player.state !== undefined && [State.Completed, State.Discontinued].includes(player.state);
    
  • 修正变量类型或赋初始值
    如果player本应是完整的Player对象,只是初始化时误用了Partial,可以直接调整类型或补充初始值:

    // 方式1:直接定义为Player类型并赋初始值
    let player: Player = {
      description: "",
      state: State.Completed
    };
    const isOK = [State.Completed, State.Discontinued].includes(player.state);
    
    // 方式2:保留Partial但赋完整初始值(此时state仍为可选,但实际有值)
    let player: Partial<Player> = {
      description: "",
      state: State.Completed
    };
    // 若需确保类型安全,可转成Player类型
    let fullPlayer = player as Player;
    const isOK = [State.Completed, State.Discontinued].includes(fullPlayer.state);
    
  • 放宽数组参数类型
    将数组的类型放宽为允许undefined,这样includes()就能接收player.state:

    const states = [State.Completed, State.Discontinued] as const;
    const isOK = (states as readonly (State | undefined)[]).includes(player.state);
    

内容的提问来源于stack exchange,提问作者Fred Hors

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:50:36