[英]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.