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