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

TypeScript中as const场景下includes类型不兼容报错原因解析

TypeScript中Array.includes()类型不匹配报错原因解析

问题代码

const UserStatus = {
  gaming: 'gaming',
  sleeping: 'sleeping',
  reading: 'reading',
  movie: 'movies',
  idle: 'idle',
} as const;

type UserStatus = keyof typeof UserStatus;

const u: {name: string, s: UserStatus} = {name: "Joe", s: UserStatus.gaming};

const i = [UserStatus.sleeping, UserStatus.idle].includes(u.s);

console.log(i);

报错信息

Argument of type "gaming" | "sleeping" | "reading" | "idle" | "movie" is not assignable to parameter of type "sleeping" | "idle".
  Type "gaming" is not assignable to type "sleeping" | "idle".(2345)
const u: {
    name: string;
    s: UserStatus;
}

报错原因

  1. 数组类型的精确推断:由于UserStatus被标记为as const,TypeScript会把数组[UserStatus.sleeping, UserStatus.idle]的类型严格推断为('sleeping' | 'idle')[],即这个数组只能包含sleeping和idle这两个具体字符串值。
  2. 变量类型的范围差异:u.s的类型是UserStatus,对应联合类型'gaming' | 'sleeping' | 'reading' | 'movie' | 'idle',这个类型的覆盖范围远大于数组includes方法要求的参数类型('sleeping' | 'idle')。
  3. 严格类型校验的限制:TypeScript的类型系统会严格检查参数与方法要求的类型是否匹配。因为u.s可能取到gaming、reading这类不在数组元素范围内的值,而includes要求参数必须是数组元素类型的子类型,所以触发了类型不兼容的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:54:55