我想知道为什么没有用于定义操作类型字符串的修饰器,而是每次声明操作名称时都声明一个静态常量/变量。
我是这样想的:
function ActionType(type: string) {
return (ctor: Function) => {
ctor.type = type;
}
}
@ActionType('Hello World !')
class MyAction {
}我不确定将type添加到构造函数是否等同于静态成员,但我知道在使用装饰器之后,console.log(MyAction.type)会像声明静态成员一样打印Hello World !。
这样行得通吗?
发布于 2019-03-13 02:34:21
我想你是在找这样的东西:
function decorate(typ: string) {
return function <T extends {new (...args) }>(cls: T): T & { type: string } {
return class extends cls {
static type: string = typ;
}
}
}
@decorate("")
class Foo {
static bar() {
return 42
}
}
Foo.type // ''奇怪的部分:
(arg: T)表示arg是T类的实例。arg: { new (...args): T}表示arg是T类(不是实例)
&运算符是来自两个接口的合并类型,例如{ key1: string } & { key2: number }等于{ key1: string, key2: number }
return class extends cls意味着我们返回扩展了cls的匿名类(在这种情况下是Foo)。我们将静态类型: string添加到其中,因为我们通过T & { type: string }部件强制这样做
https://stackoverflow.com/questions/55125584
复制相似问题