How to get a list of keys from a generic object type?
generic Class:
export class GenericExample<T>{
private _keys: string[];
constructor()
{
this.keys = // all keys of generic type T
}
get keys(obj: T[])
{
return this._keys;
}
}
example usage with interface:
export interface someInterface { foo: string; bar: string; };
export class someClass { id: number; name: string; };
let example1 = new GenericExample<someType>();
example1.getKeys([]) // output: ["foo", "bar" ]
example usage with class:
let example2= new GenericExample<someClass>();
example2.getKeys([]) // output: ["id", "name" ]
The generic type is only a type, so you need to pass in an actual object that matches it to the constructor. Only then can you get the keys.
Also, a getter doesn't take any parameters, so I removed them.
Something like this:
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With