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

如何在TypeScript中从类型(而非实例)枚举属性名称?

如何从TypeScript类类型中枚举属性名称?

你提到的这个需求很常见——想要从User类本身(而非实例)拿到它的属性名数组['Name', 'Surname', 'BirthDate']。因为TypeScript的类型信息在运行时会被擦除,所以我们需要结合编译时类型工具和运行时API来实现,下面给你两种实用的方案:

方案一:借助类原型自动获取(运行时)

TypeScript编译后的ES6类,实例属性会被挂载到类的原型上。我们可以用Object.getOwnPropertyNames获取原型上的所有属性,再过滤掉constructor这个特殊方法,就能得到目标属性名:

class User {
  Name: string;
  Surname: string;
  BirthDate: Date;

  constructor(name: string, surname: string, birthDate: Date) {
    this.Name = name;
    this.Surname = surname;
    this.BirthDate = birthDate;
  }
}

// 提取类原型上的实例属性,排除constructor
const userPropertyNames = Object.getOwnPropertyNames(User.prototype).filter(prop => prop !== 'constructor');
console.log(userPropertyNames); // 输出: ['Name', 'Surname', 'BirthDate']

这个方法的好处是自动生成,不需要手动维护属性名数组,适合属性较多或者经常变动的类。如果你的类有静态属性,记得用Object.getOwnPropertyNames(User)(直接取类本身,而非原型)来获取静态属性名。

方案二:编译时验证+手动维护(类型安全)

如果更关注类型正确性,避免拼写错误,可以结合TypeScript的keyof工具类型,让编译器帮你校验属性名数组的合法性:

class User {
  Name: string;
  Surname: string;
  BirthDate: Date;

  constructor(name: string, surname: string, birthDate: Date) {
    this.Name = name;
    this.Surname = surname;
    this.BirthDate = birthDate;
  }
}

// 编译时获取User的所有属性名类型
type UserPropertyNames = keyof User;

// 手动定义数组,TypeScript会自动校验每个元素是否为合法的属性名
const userProps: UserPropertyNames[] = ['Name', 'Surname', 'BirthDate'];
console.log(userProps); // 输出: ['Name', 'Surname', 'BirthDate']

这种方法的优势是类型安全——如果你不小心写错了属性名(比如写成'name'小写),TypeScript会直接报错。缺点是需要手动维护数组,适合属性较少且不常变动的类。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:49:45