【发布时间】:2020-06-03 20:25:49
【问题描述】:
我目前有一个函数需要接受类类型,实例化类并返回模板类型的实例。我收到一个错误:'ActorType' only refers to a type, but is being used as a value here.
spawnActor<ActorType extends Actor>(actorClass: typeof ActorType): ActorType {
let actorObject = new actorClass();
actorObject.sayHello(); // specific to Actor
return actorObject;
}
目前我发现如果我使参数类型不使用模板actorClass: Actor 而不是actorClass: ActorType,则声明有效。但是,当调用该函数时,我必须明确指定模板类型,因为无法从传递给 actorClass 参数的类中推断出它。
spawnActor<ActorType extends Actor>(actorClass: typeof Actor): ActorType {
let actorObject = (new actorClass() as ActorType); // must cast to template type
actorObject.sayHello(); // specific to Actor
return actorObject;
}
let a = spawnActor<MyActorClass>(MyActorClass); // have to give template type for a to have correct type
//let a = spawnActor(MyActorClass); // ideally it would be inferred
【问题讨论】:
标签: typescript class templates