简体   繁体   中英

Annotate a class using declaration file? — TypeScript

I have a decorator which adds a property into the class as:

function Service(constructor: any): any {
  constructor.Instance = {};
}

@Service
class MyService {

}

The property will be static as public static Instance: MyService , but i have a bunch of classes, i just can't add public static Instance: ServiceType , in every class. What I did is:

class BaseService<T> {
  public static Instance: T; // Static members cannot reference class type parameters.ts(2302)
}

@Service
class MyService extends BaseService<MyService> {

}

Which should work but I got Static members cannot reference class type parameters.ts(2302) , so i tried this as:

function BaseService<T>() {
  abstract class BaseService {
    public static Instance: T;
  }
  return BaseService;
}

@Service
class MyService extends BaseService<MyService> { // Type '<T>() => typeof BaseService' is not a constructor function type.ts(2507)

}

this also not worked, so i think can we make a declaration file, in which we can declare BaseService class as a type, but I am confused how to use that type? implements? extends? , but Type can't be extended or implemented. As the Instance already exists in the class, what i need exactly is to annotate the class with that property, so that i can access it like MyService.Instance , and i don't want to add explicitly in all classes. Any suggestions?

I have choosen an other way of doing it, here's the link . In short the decorator functionality I was doing is a bit difficult, but now I have got an other way of doing it, so it solves my question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM