Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a static variable from a generic class?

I have many class with their static variables, like this:

user.ts:

export class User {
  static modelKey = 'user';

  // other variables
}

car.ts:

export class Car {
  static modelKey = 'car';

  // other variables
}

And somewhere I want just call the DataSource (see below) like this:

const dataSource = new DataSource<Car>();

data-source.ts:

export class DataSource<T> {

  constructor() {
    console.log(T.modelKey); // won't compile
  }  
}

Of course, it won't compile because I can't simple use T.<variable>. So, my question is: how can I accomplish this?

Playground

like image 906
dev_054 Avatar asked Oct 30 '22 04:10

dev_054


1 Answers

You can't access properties on types, only on arguments passed in, because types don't exist at runtime.

But you can pass in your class to your constructor, and then access properties on that.

e.g.

export class User {
  static modelKey = 'user';

  // other variables
}
export class Car {
  static modelKey = 'car';

  // other variables
}

interface ModelClass<T> {
  new (): T;
  modelKey: string;
}

export class DataSource<T> {

  constructor(clazz: ModelClass<T>) {
    console.log('Model key: ', clazz.modelKey); // will compile
  }  
}

new DataSource(Car);

Playground link

like image 175
GregL Avatar answered Dec 19 '22 13:12

GregL