Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 编译器能否推断类构造函数的返回类型?_Typescript - Fatal编程技术网

Typescript 编译器能否推断类构造函数的返回类型?

Typescript 编译器能否推断类构造函数的返回类型?,typescript,Typescript,给定一个类定义: class Foo { } 以及接受类函数的类型参数化函数: function bar<TInstance, TClass extends { new (): TInstance }>(t: TClass): TInstance { return new t() // more complicated in reality, focus on the compiler! } 但是,这里的x类型是{},而不是Foo 我可以使用显式类型参数调用它: con

给定一个类定义:

class Foo {

}
以及接受类函数的类型参数化函数:

function bar<TInstance, TClass extends { new (): TInstance }>(t: TClass): TInstance {
    return new t() // more complicated in reality, focus on the compiler!
}
但是,这里的
x
类型是
{}
,而不是
Foo

我可以使用显式类型参数调用它:

const x = bar<Foo, typeof Foo>(Foo)
const x=bar(Foo)
。。。但那真是陈词滥调


有没有办法通过此方法获得类型推断以避免样板文件?

如果函数签名过于复杂,此版本可以工作:

function bar<TInstance>(t: { new (): TInstance }): TInstance {
    return new t();
}

const x = bar(Foo); // x is of type Foo
功能栏(t:{new():TInstance}):TInstance{
返回新的t();
}
常数x=bar(Foo);//x是Foo类型

如果函数签名过于复杂,此版本可以工作:

function bar<TInstance>(t: { new (): TInstance }): TInstance {
    return new t();
}

const x = bar(Foo); // x is of type Foo
功能栏(t:{new():TInstance}):TInstance{
返回新的t();
}
常数x=bar(Foo);//x是Foo类型

太好了,我早该想到的。谢谢太好了,我早该想到的。谢谢