如何获取泛型类型(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" ]

泛型类型只是一个类型,因此需要将与它匹配的实际对象传递给构造函数。只有这样你才能拿到钥匙。

此外,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"]

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

最新更新