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

TypeScript定义Cell类型遇ts(2749)错误:值用作类型问题

扫雷游戏TypeScript类型定义错误排查

问题场景

我正在用TypeScript开发扫雷游戏,定义Cell类型时遇到报错,具体代码和错误信息如下:

无法运行的代码

const bomb = "💣";
const flag = "🚩";

export type Cell = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | bomb | flag;

export type Board = Array<Array<Cell>>;

报错信息

'bomb' refers to a value, but is being used as a type here. Did you mean 'typeof bomb'?ts(2749)

可正常运行的代码

export type Cell = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | "&#128163;" | "&#128681;";

错误原因

TypeScript里值和类型是完全独立的两个体系:

  • 你定义的bomb和flag是运行时的值(const变量);
  • 而Cell是编译时的类型,类型定义只能使用类型语法,不能直接引用值。

直接写字符串字面量"&#128163;"合法,是因为字符串字面量本身可以作为TypeScript的字面量类型使用。


解决方法

如果想复用bomb和flag的字符串值同时作为类型,有两种常用方案:

方案1:用typeof提取值的类型

通过typeof获取变量的类型,加入联合类型即可:

const bomb = "&#128163;";
const flag = "&#128681;";

export type Cell = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | typeof bomb | typeof flag;

export type Board = Array<Array<Cell>>;

方案2:定义字面量类型别名

先把字符串字面量定义成类型别名,再同时导出值和类型,方便代码复用:

type Bomb = "&#128163;";
type Flag = "&#128681;";

export const bomb: Bomb = "&#128163;";
export const flag: Flag = "&#128681;";

export type Cell = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Bomb | Flag;
export type Board = Array<Array<Cell>>;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:50:26