2016-09-08 6 views
2

Javaでは、タイプ "クラス"を使用してclass to a methodをパラメータとして指定できます。私はtypescriptドキュメントで何も見つからなかった - クラスをメソッドに渡すことは可能ですか?もしそうなら、「any」型にそのようなクラス型が含まれていますか?Typescriptに "Class"の型がありますか?それに「any」も含まれていますか?

背景:私はWebstormに問題があります。私はクラスを@ViewChild(...)に渡すことはできませんと言っています。しかし、Typescriptコンパイラは文句を言っていません。 @ViewChild()の署名は"Type<any> | Function | string"と思われるので、クラスが含まれているかどうかは疑問です。

答えて

2

あなたはtypescriptですに求めている何のために同等とは、例えば、タイプ{ 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のクラスを渡す必要はありません

function myFunction(myClassParam: Class) { 
} 

class MyClass {} 

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

ここ

はクラスのみを含むタイプの例です細かい作業:

var func: Function = MyClass; // ok 
1

これは動作するはずです - delcare aJavaおよびJavaScriptでタイプ

// 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 

と同様の例hereあり

0

継承モデルが異なっています。 Javaでは、クラスのすべてのインスタンス間で共有されるClassオブジェクトがあります。 JavaScriptはプロトタイプの継承を使用しており、Classオブジェクトのようなものはありません。

実行可能コードの継承モデルを変更せずに、TypeScriptとES6の両方にclassキーワードがあります。

+1

実際には、typescriptでファーストクラスのエンティティとしてクラスを処理できます。クラスのリストを持つことができ、クラスの静的メソッドは通常のオブジェクトのメソッドと同じように呼び出すことができます。クラス**は、書体の土地にあるオブジェクトです。 – Alex

関連する問題