是否有“类"的类型?在打字稿?并且“任何"包括它? [英] Is there a type for "Class" in Typescript? And does "any" include it?
问题描述
在 Java 中,您可以使用Class"类型将方法的类作为参数.我在打字稿文档中没有找到任何类似的东西 - 是否可以将类传递给方法?如果是,any"类型是否包括此类类类型?
In Java, you can give a class to a method as a parameter using the type "Class". I didn't find anything similar in the typescript docs - is it possible to hand a class to a method? And if so, does the type "any" include such class-types?
背景:我在使用 Webstorm 时遇到问题,告诉我我无法在 Angular 2 中将类移交给 @ViewChild(...)
.但是,Typescript 编译器没有抱怨.@ViewChild()
的签名好像是"Type
,所以不知道有没有包含类.
Background: I'm having an issue with Webstorm, telling me that I cannot hand over a class to @ViewChild(...)
in Angular 2. However, the Typescript compiler does not complain. The signature of @ViewChild()
seems to be "Type<any> | Function | string"
, so I wonder if any includes Classes or not.
推荐答案
你在打字稿中要求的等价物是类型 { new(): Class }
,例如:>
The equivalent for what you're asking in typescript is the type { new(): Class }
, for example:
class A {}
function create(ctor: { new(): A }): A {
return new ctor();
}
let a = create(A); // a is instanceof A
(代码在操场上)
上面的代码将只允许构造函数没有参数的类.如果你想要任何类,使用 new (...args: any[]) =>类
The code above will allow only classes whose constructor has no argument. If you want any class, use new (...args: any[]) => Class
这篇关于是否有“类"的类型?在打字稿?并且“任何"包括它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!