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

TypeScript类型收窄无效:number无法赋值给Level类型求助

解决TypeScript中includes无法正确收窄字面量联合类型的问题

问题出在TypeScript无法通过Array.includes()自动将number类型收窄到你的Level字面量联合类型。因为[1,2,3,4,5,6]会被默认推断为number[],调用includes(level)后,TypeScript无法确定level具体是1-6中的哪一个字面量,所以仍会认为它是number类型。

以下是几种可行的解决方法:

方法1:使用类型断言

既然你已经通过includes确认了level在1-6范围内,可以直接用类型断言明确告诉TypeScript它的实际类型:

type Level = 1 | 2 | 3 | 4 | 5 | 6;

onSelect={(level: number) => {
  if ([1, 2, 3, 4, 5, 6].includes(level)) {
    editor.commands.setHeading({
      level: level as Level,
    });
  } else if (level === 7) {
    editor.commands.setParagraph();
  }
}}

方法2:自定义类型守卫函数

编写一个类型守卫函数,让TypeScript能精准识别level是否符合Level类型:

type Level = 1 | 2 | 3 | 4 | 5 | 6;

function isLevel(level: number): level is Level {
  return level >= 1 && level <= 6;
}

onSelect={(level: number) => {
  if (isLevel(level)) {
    editor.commands.setHeading({
      level,
    });
  } else if (level === 7) {
    editor.commands.setParagraph();
  }
}}

方法3:显式指定数组类型

给数组指定Level[]类型,让includes方法的类型检查逻辑更准确:

type Level = 1 | 2 | 3 | 4 | 5 | 6;

onSelect={(level: number) => {
  if (([1, 2, 3, 4, 5, 6] as Level[]).includes(level)) {
    editor.commands.setHeading({
      level,
    });
  } else if (level === 7) {
    editor.commands.setParagraph();
  }
}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:35:39