2017-06-13 37 views
0

在TypeScript中,當創建函數接口並將其用作另一個函數(即期望回調函數)期望的類型時,並且回調函數的參數是一個數組類。該類型檢查似乎沒有能夠處理它:函數接口中類的數組類型檢查

"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)}); 

在這種情況下,我相信到B的第二個呼叫失效類型檢查,因爲它的時候沒想到類實例的數組,而是一種原始的這種作爲字符串:

"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)}); 

哪些失敗,類型檢查:

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'. 

我找不到試圖尋找答案,我使用打字稿2時對此事情。 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的快速解答和參考文檔! –