【问题标题】:Type for function that takes a class as argument, and returns an instance of that class将类作为参数并返回该类的实例的函数类型
【发布时间】:2016-04-25 18:04:59
【问题描述】:

我有一个实例化函数,它返回所提供类的实例:

declare type ClassType = { new (): any }; // alias "ParameterlessConstructor"

function getInstance(constructor: ClassType): any {
    return new constructor();
}

我怎样才能使函数返回constructor 参数的实例 而不是any,以便我可以为该函数的使用者实现类型安全?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    嗯,这非常简单,我只需要绕过我自己的代码设置的界限。


    关键是将constructor参数指定为返回泛型类型的可新类型,它与@返回的相同泛型类型T 987654323@函数:

    function getInstance<T>(constructor: { new (): T }): T {
        return new constructor();
    }
    

    这将产生正确的结果:

    class Foo {
        public fooProp: string;
    }
    
    class Bar {
        public barProp: string;
    }
    
    var foo: Foo = getInstance(Foo); // OK
    var bar: Foo = getInstance(Bar); // Error: Type 'Bar' is not assignable to type 'Foo'
    

    【讨论】:

      猜你喜欢
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 2021-08-13
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      相关资源
      最近更新 更多