首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获取泛型类型(TypeScript)的键列表?

问如何获取泛型类型(TypeScript)的键列表?
EN

Stack Overflow用户
提问于 2021-07-20 17:29:02
回答 2查看 153关注 0票数 0

如何从泛型对象类型中获取键的列表?

泛型类:

代码语言:javascript
复制
export class GenericExample<T>{
   
 private _keys: string[];

 constructor()
 {
      this.keys = // all keys of generic type T
 }

  get keys(obj: T[])
  {
    return this._keys;
  }
}

接口的用法示例:

代码语言:javascript
复制
export interface someInterface { foo: string; bar: string; };
export class someClass { id: number; name: string; };

let example1 = new GenericExample<someType>();
example1.getKeys([]) // output: ["foo", "bar" ]

使用class的示例用法:

代码语言:javascript
复制
let example2= new GenericExample<someClass>();
example2.getKeys([]) // output: ["id", "name" ]
EN

回答 2

Stack Overflow用户

发布于 2021-07-20 17:32:24

您可以只使用Object.keys(obj),它将返回对象键的数组。(在本例中为["foo", "bar"]

票数 0
EN

Stack Overflow用户

发布于 2021-07-20 18:46:38

泛型类型只是一个类型,所以您需要传入一个与构造函数匹配的实际对象。只有这样你才能拿到钥匙。

另外,getter不接受任何参数,所以我删除了它们。

如下所示:

代码语言:javascript
复制
export class GenericExample<T>{
   
 private _keys: Array<keyof T>;

 constructor(obj: T)
 {
      // The keys from generic type T are only types,
      // so you need to pass in an object that matches T
      // to the constructor. Then we can do this:
      this._keys = Object.keys(obj) as Array<keyof T>;
 }

  get keys()
  {
    return this._keys;
  }
}

// Usage

const obj = { foo: "foo", bar: "bar" };

const instance = new GenericExample(obj);

// instance.keys infer to ("foo" | "bar")[] and will return ["foo", "bar"]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68452558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档