Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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" ]
like image 516
Patrick Avatar asked Oct 21 '25 10:10

Patrick


1 Answers

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

like image 139
mekwall Avatar answered Oct 23 '25 01:10

mekwall