2016-09-08 210 views
2

在Java中,您可以使用“Class”类型将class to a method作为参数。在打字稿中我没有发现任何类似的东西 - 是否有可能将一个班级交给一个方法?如果是这样,“any”类型是否包含这样的类型?在Typescript中是否有“Class”类型?并且“any”包含它吗?

背景:我遇到了Webstorm的一个问题,告诉我我无法在Angular 2中将类移交给@ViewChild(...)。但是,Typescript编译器不会投诉。 @ViewChild()的签名似乎是"Type<any> | Function | string",所以我想知道是否有包括类或不。

回答

2

等效为你问的打字稿是什么{ new(): Class }的类型,例如:

class A {} 

function create(ctor: { new(): A }): A { 
    return new ctor(); 
} 

let a = create(A); // a is instanceof A 

code in playground

+0

请注意,'{new():Class}'也可以写成'new()=> Class'。 https://github.com/Microsoft/TypeScript/blob/v2.6.1/doc/spec.md#3.8.9 –

1

是有可能手一类的方法?如果是这样,“any”类型是否包含这样的类型?

是的,是的。 any包括每种类型。

这里有一个类型仅包括类的例子:然后用它

type Class = { new(...args: any[]): any; }; 

function myFunction(myClassParam: Class) { 
} 

class MyClass {} 

myFunction(MyClass); // ok 
myFunction({}); // error 

你不应该有一个类传递一个错误Function,但因为这应该工作正常:

var func: Function = MyClass; // ok 
1

这应该工作 - delcare a type类型

// just two different classes 
class MyClass {} 
class OtherClass { 
    constructor(protected IsVisible: boolean) {} 
} 

// here we declare our type named "Type" 
type Type = Function; 

// we will consume just params of a Type (classes) 
function take(type: Type){ 
} 


// build will fail 
take(1);   // not a Type 
take("A")   // not a Type 
take(new Date()); // not a Type 

// will be working 
take(MyClass); // this is a type 
take(OtherClass); // this is a type 

a working example

或者类似的一个接口

// just two different classes 
class MyClass {} 
class OtherClass { 
    constructor(protected IsVisible: boolean) {} 
} 

// here we declare our type named "Type" 
interface Type extends Function {} 

// we will consume just params of a Type (classes) 
function take(type: Type){ 
} 


// build will fail 
take(1);   // not a Type 
take("A")   // not a Type 
take(new Date()); // not a Type 

// will be working 
take(MyClass); // this is a type 
take(OtherClass); // this is a type 

例在Java和JavaScript here

0

的遗传模型是不同的。在Java中,您有一个在该类的所有实例之间共享的Class对象。 JavaScript使用原型继承,并没有像Class对象那样的东西。

TypeScript和ES6的class关键字都只是一个语法糖而不改变可执行代码的继承模型。

+1

实际上,您可以将类作为打字稿中的第一类实体来处理。你可以有一个类的列表,这些类的静态方法可以像普通对象上的方法那样调用。类**是打字稿地中的一个对象。 – Alex

相关问题