typescript 使用带有 `typeof T` 的泛型类型参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40249906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a generic type argument with `typeof T`
提问by Aaron Beall
I have a factory-like function that is meant to return an sub-class instance of BaseApi
. It currently looks something like this (trimmed out irrelevant parts):
我有一个类似工厂的函数,用于返回BaseApi
. 它目前看起来像这样(修剪掉不相关的部分):
function getApi<T extends BaseApi>(apiClass: typeof BaseApi): T {
return new apiClass();
}
And I use it like this:
我像这样使用它:
const someApi = getApi<SomeApi>(SomeApi);
This works, but I would like <SomeApi>
to be inferred by virtue of the fact that I'm passing the SomeApi
constructor in. If I omit <SomeApi>
then someApi
is inferred to be of type BaseApi
, not SomeApi
. Worse, there's really no compiler correlation between <T extends BaseApi>
and typeof BaseApi
being the same thing, so you can incorrectly do something like getApi<SecondApi>(FirstApi)
without a compiler error.
这是有效的,但我想<SomeApi>
根据我正在传递SomeApi
构造函数的事实来推断。如果我省略,<SomeApi>
则someApi
推断为类型BaseApi
,而不是SomeApi
。更糟的是,真的没有编译器之间的相关性<T extends BaseApi>
,并typeof BaseApi
为同样的事情,这样你就可以正确地做这样的事情getApi<SecondApi>(FirstApi)
没有一个编译器错误。
So I tried defining the apiClass
as typeof T
:
所以我尝试将其定义apiClass
为typeof T
:
function getApi<T extends BaseApi>(apiClass: typeof T): T {
return new apiClass();
}
And I found that TS did not understand this usage of T
. Is there any way to do this?
而且我发现 TS 不理解T
. 有没有办法做到这一点?
回答by Ryan Cavanaugh
What you actually want is new() => T
, since you intend to use the argument as a constructor and produce a T
. Even if you could write typeof T
, that wouldn't be what you want, since T
might not have a zero-argument constructor.
您真正想要的是new() => T
,因为您打算将参数用作构造函数并生成T
. 即使您可以编写typeof T
,那也不是您想要的,因为T
可能没有零参数构造函数。
Remember that the typeof
operator takes a valueand produces a value. T
is already a type; it is not a value.
请记住,typeof
运算符接受一个值并产生一个值。T
已经是一个类型;它不是一个值。
Naturally, this is addressed in the TypeScript FAQ https://github.com/Microsoft/TypeScript/wiki/FAQ#why-cant-i-write-typeof-t-new-t-or-instanceof-t-in-my-generic-function
自然,这在 TypeScript 常见问题解答https://github.com/Microsoft/TypeScript/wiki/FAQ#why-cant-i-write-typeof-t-new-t-or-instanceof-t-in-my 中得到解决-通用功能