如何从泛型对象类型中获取键的列表?
泛型类:
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" ]使用class的示例用法:
let example2= new GenericExample<someClass>();
example2.getKeys([]) // output: ["id", "name" ]发布于 2021-07-20 17:32:24
您可以只使用Object.keys(obj),它将返回对象键的数组。(在本例中为["foo", "bar"]
发布于 2021-07-20 18:46:38
泛型类型只是一个类型,所以您需要传入一个与构造函数匹配的实际对象。只有这样你才能拿到钥匙。
另外,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"]https://stackoverflow.com/questions/68452558
复制相似问题