Arthur Foucher
Arthur Foucher

Reputation: 33

How can I access class instance members and methods from the class itself

I'm trying to write a function that will create a instance from a class and do some operations on some of its members

function presetInstance<T>(baseClass: any, members: Array<keyof T>) {
  const instance: T = new baseClass();

  // ...
}

It works but it leads to code that feels like it should improved:

const instance = presetInstance<BaseClass>(BaseClass, ['foo', 'bar']);

Is there a way to only write this ?

const instance = presetInstance(BaseClass, ['foo', 'bar']);

Upvotes: 2

Views: 43

Answers (1)

Fabian Lauer
Fabian Lauer

Reputation: 9907

Yes, you can use a type such as this:

interface IConstructor<T> {
    new(): T;
}

Now, change the function signature to:

presetInstance<T>(baseClass: IConstructor<T>, members: Array<keyof T>)

This way, typescript can infer that baseClass creates an instance of T when constructed with new.

TS Playground example here.

Upvotes: 2

Related Questions