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 | "💣" | "🚩";
错误原因
TypeScript里值和类型是完全独立的两个体系:
- 你定义的
bomb和flag是运行时的值(const变量); - 而
Cell是编译时的类型,类型定义只能使用类型语法,不能直接引用值。
直接写字符串字面量"💣"合法,是因为字符串字面量本身可以作为TypeScript的字面量类型使用。
解决方法
如果想复用bomb和flag的字符串值同时作为类型,有两种常用方案:
方案1:用typeof提取值的类型
通过typeof获取变量的类型,加入联合类型即可:
const bomb = "💣"; const flag = "🚩"; 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 = "💣"; type Flag = "🚩"; export const bomb: Bomb = "💣"; export const flag: Flag = "🚩"; export type Cell = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Bomb | Flag; export type Board = Array<Array<Cell>>;
内容的提问来源于stack exchange,提问作者AG_1380
相关产品推荐
相关产品推荐

