繁体   English   中英

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

[英]How to get a list of keys of generic type (TypeScript)?

如何从通用对象类型获取键列表?

通用类:

export class GenericExample<T>{
   
 private _keys: string[];

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

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

接口使用示例:

export interface someInterface { foo: string; bar: string; };
export class someClass { id: number; name: string; };

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

类的示例用法:

let example2= new GenericExample<someClass>();
example2.getKeys([]) // output: ["id", "name" ]

您可以只使用Object.keys(obj)它将返回对象键的数组。 (在这种情况下, ["foo", "bar"]

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

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

像这样的东西:

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"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM