2016-09-08 243 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

相關問題