Home > Mobile >  Class as an argument
Class as an argument

Time:06-20

I've just started using typescript and faced with the next implementation issue. I'm trying to implement a class that takes another class as an argument. the issue is that it can be any class, but I want to specify some possible class properties or methods. Let's say that this class can have singleton static property. I try to use Class generic:

type Class<T> = new (...args: any[]) => T;

class ClassResource {
  private _resource;
  private _singleton;
  
  constructor(resource: Class<any>) {
    this._resource = resource;
    this._singleton = resource.singleton;
  }

  // some methods

  getClassInstance() {
    return new this._resource();
  }
}

but got the next error:

Property 'singleton' does not exist on type 'Class'

How can I correctly type this "abstract" class and describe only some specific possible properties, but not limited to them?

CodePudding user response:

All you have to do is mention in your type that the class must have a singleton property.


type _Class<T>= new (...args: any[]) => T;

type ClassType<T> =  _Class<T> & {
    singleton: T
}

class ClassResource {
  private _resource;
  private _singleton;
  
  constructor(resource: ClassType<any>) {
    this._resource = resource;
    this._singleton = resource.singleton;
  }

  // some methods

  getClassInstance() {
    return new this._resource();
  }
}


class A {
    
    static singleton = new A();

    getHello() {
        return ''
    }
}

new ClassResource(A); //works

class B  {
    getHello() {
        return ''
    }
}

new ClassResource(B); // doesn't work

  • Related