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。
謝謝Nitzan的快速解答和參考文檔! –