2017-06-13 9 views
0

関数型インターフェイスを作成し、それを別の関数(つまりコールバックを期待する関数)が期待する型として使用する場合、コールバック関数のパラメータはaクラス。私はそれがクラスのインスタンスの配列を期待していないときとBの2番目の呼び出しは、型チェックに失敗しなければならないと考えている。この場合関数のインターフェイスのクラスの配列の型チェック

"use strict"; 

class A { 
    /* no-op */ 
} 

interface C { 
    (s: Array<A>): void 
} 

const B = (c: C) => { 
    c(["Hello World!"]); 
}; 

B((s: Array<A>) => {console.log("Should work", s)}); 
B((s: A) => {console.log("Should not work", s)}); 

、代わりに原始的な:型チェックは、それを処理することができていないようです私は答えを検索しようとすると、私は活字体2を使用していたときに、このについての何かを見つけることができませんでした

test.ts(12,3): error TS2345: Argument of type '(s: string) => void' is not assignable to parameter of type 'C'. 
    Types of parameters 's' and 's' are incompatible. 
    Type 'string[]' is not assignable to type 'string'. 

"use strict"; 

interface C { 
    (s: Array<string>): void 
} 

const B = (c: C) => { 
    c(["Hello World!"]); 
}; 

B((s: Array<string>) => {console.log("Should work", s)}); 
B((s: string) => {console.log("Should not work", s)}); 

と型チェックを失敗:文字列として。 3.4。

答えて

0

あなたが任意のコンパイルエラーを取得していない理由は、あなたのAクラスが空で、typescript is based on structural subtypingので、空のクラス/オブジェクトは、たとえば、すべてのものと一致していることである:

class A {} 

let a1: A = 4; 
let a2: A = true; 
let a3: A = "string"; 

すべての罰金、コンパイルエラーと。

あなたはクラスAにメンバーを紹介するとき、あなたがエラーを取得を開始:

class A { 
    dummy: number; 
} 

let a1: A = 4; // ERROR: Type '4' is not assignable to type 'A' 
let a2: A = true; // ERROR: Type 'true' is not assignable to type 'A' 
let a3: A = "string"; // ERROR: Type '"string"' is not assignable to type 'A' 

const B = (c: C) => { 
    c(["Hello World!"]); // ERROR: Argument of type 'string[]' is not assignable to parameter of type 'A[]' 
}; 

B((s: A) => { console.log("Should not work", s); }); // ERROR: Argument of type '(s: A) => void' is not assignable to parameter of type 'C' 
+0

は、ドキュメントへの迅速な答えや参考のためにあなたにNitzanをありがとう! –

関連する問題