【问题标题】:Typescript template class typeof打字稿模板类 typeof
【发布时间】: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


    【解决方案1】:

    typeof 运算符一般不会获取类的构造函数;它获取具有特定名称的 value 的类型。您遇到的困惑是,使用 class Foo {} 声明的类既创建了一个名为 Foo 的类型(类的实例类型),又创建了一个名为 Foo (类的构造函数) ),然后typeof Foo 是该值的类型。但是对于泛型类型参数ActorType,没有名为ActorType 的值供您获取typeof ActorType 的类型......即使有这样的值,它也不太可能变成成为ActorType 实例的构造函数。类型和值之间的区别很重要且令人困惑,我之前已经talked at length 讨论过这个问题。

    您真正需要的是"newable" call signature。如果您的实例类型是T,那么生成T 实例的无参数构造函数的类型为:

    new() => T;
    

    或等效:

    { new(): T }
    

    如果您使用new() =&gt; ActorType 而不是typeof ActorType,您应该能够完成这项工作。希望有帮助;祝你好运!

    【讨论】:

    • 谢谢,正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 2023-01-11
    • 2019-04-12
    • 2017-09-29
    • 2018-05-22
    相关资源
    最近更新 更多