简体   繁体   English

使用声明文件注释 class? — TypeScript

[英]Annotate a class using declaration file? — TypeScript

I have a decorator which adds a property into the class as:我有一个装饰器,它将一个属性添加到 class 中,如下所示:

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. 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:哪个应该可以,但我得到了Static members cannot reference class type parameters.ts(2302) ,所以我试了这个

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?这也不起作用,所以我想我们可以制作一个声明文件,在其中我们可以将BaseService class 声明为一种类型,但我很困惑如何使用该类型? implements? extends? , but Type can't be extended or implemented. ,但 Type 无法扩展或实现。 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.由于Instance已经存在于 class 中,我需要的是用该属性注释 class ,以便我可以像MyService.Instance一样访问它,我不想在所有类中显式添加。 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.简而言之,我正在做的装饰器功能有点困难,但现在我有了另一种方法,所以它解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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