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

如何正确声明并初始化TypeScript类的enum枚举类型属性?

错误原因

你之所以出现TS2304: Cannot find name 'enum'报错,是因为TypeScript中enum是独立的类型声明关键字,不能直接内联写在类属性的类型标注位置,你的写法会让TS把enum当做一个不存在的类型名去检索,自然报错。

正确实现方式

方案1:先声明独立的枚举类型(最常用)

提前定义好Direction枚举类型,再给类的direction属性绑定该类型即可,TS的数字枚举默认从0开始自增,完全符合你UP=0、DOWN=1的需求:

// 提前声明枚举类型,其他文件需要使用的话可以加export导出
enum Direction {
  UP, // 默认值为0
  DOWN, // 自动自增为1
  LEFT, // 自动赋值为2
  RIGHT // 自动赋值为3
}

export default class Character{
    public x: number;
    public y: number;
    public animate: Boolean = true;
    // 绑定枚举类型,可根据需求设置初始默认值
    public direction: Direction = Direction.UP;

    constructor(x: number, y: number){
        this.x = x;
        this.y = y;
    }
}

使用的时候直接通过Direction枚举赋值即可:

const char = new Character(10, 20);
char.direction = Direction.DOWN;

方案2:将枚举作为类的静态成员(避免全局污染)

如果你不希望枚举暴露在全局作用域,可以把它挂载为类的静态只读成员:

export default class Character{
    // 静态只读枚举,全类共享,Object.freeze防止被意外修改
    public static readonly Direction = Object.freeze({
        UP: 0,
        DOWN: 1,
        LEFT: 2,
        RIGHT: 3
    } as const);

    public x: number;
    public y: number;
    public animate: Boolean = true;
    // 提取静态枚举的值类型作为属性类型
    public direction: typeof Character.Direction[keyof typeof Character.Direction] = Character.Direction.UP;

    constructor(x: number, y: number){
        this.x = x;
        this.y = y;
    }
}

// 外部使用示例
const char = new Character(10, 20);
char.direction = Character.Direction.RIGHT;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 23:36:06