【发布时间】:2016-05-24 05:34:40
【问题描述】:
考虑一下failing example:
function DecorateClass<T>(instantiate: (...params:any[]) => T){
return (classTarget:T) => { /*...*/ }
}
@DecorateClass((json:any) => {
//Purely example logic here, the point is that it have to return
//an instance of the class that the decorator runs on.
var instance = new Animal();
instance.Name = json.name;
instance.Sound = json.sound;
return instance;
})
class Animal {
public Name:string;
public Sound:string;
}
这里我想限制装饰器中的匿名函数始终返回相关类的实例,但上述方法不起作用,因为 T 实际上是 typeof Animal 而不是 Animal。
在一个泛型函数中,我是否可以从 typeof Animal 类型中获取类型 Animal 而不会像显式定义所有类型(如 function DecorateClass<TTypeOfClass, TClass>(...))那样冗长而烦人?
不幸的是,不支持在通用语法中使用 typeof,这是我试图让编译器理解我想要什么的最佳选择:
function DecorateClass<T>(instantiate: (json:any) => T){
return (classTarget:typeof T) => { /*...*/ } // Cannot resolve symbol T
}
【问题讨论】:
-
乍一看,这似乎是一个XY problem。您究竟想要完成什么?似乎您正在将 JSON 反序列化为类型实例,但无法确定。
-
@JohnWhite 不,这只是一个基本示例。我想要完成的是在装饰器函数的类型中拥有类实例的类型,而无需显式定义它。这种结构将应用于数百个类,我希望将装饰器的内部输入到类的实例中,我真的不喜欢必须明确定义实例类型的想法装饰器运行的类。
标签: typescript