![](/img/trans.png)
[英]TypeScript error Parameter 'props' implicitly has an 'any' type
[英]TypeScript claims no error even if parameter has the wrong type
我有一個將字典作為第一個參數的函數。 該字典以字符串為鍵,以函數為值。 問題是,如果字典中的函數簽名錯誤,TypeScript 不會抱怨!
一段代碼值 1000 字。 這是我的main.ts
:
interface MyMap {
[key: string]: (x: number) => void;
}
function f(map: MyMap, key: string, x: number) : void{
map.hasOwnProperty(key) ? map[key](x) : console.log(x)
}
const stupidMap: MyMap = {
'square': (x) => {
console.log(x*x);
return x*x; // This function should return void!!
},
'double': (x) => {
console.log(x+x);
}
}
f(stupidMap, 'square', 5) // Prints 25
f(stupidMap, 'double', 5) // Prints 10
我用tsc main.ts
編譯它,我沒有得到任何錯誤。 tsc --version
打印Version 3.7.2
。 我有兩個問題:
任何見解將不勝感激。 謝謝!
沒有問題,因為(x: number) => void
可分配給(x: number) => number
。 這是一個證明:
type F = (x: number) => void
type Z = (x: number) => number
type ZextendsF = Z extends F ? true : false // evaluate to true
這個事實對於程序流程來說是完全沒問題的。 如果你的界面說 - 我需要一個不返回的函數,那么如果我傳遞一個返回某些東西的函數,它完全可以,因為我永遠不會使用這個返回數據。 它是類型安全的,無需擔心。
有關函數可分配性的更多詳細信息 - 比較兩個函數。 還有更多關於 TypeScript 類型行為和關系類型可分配性的細節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.