我有一个将字典作为第一个参数的函数。该字典具有字符串作为键,并具有值的功能。问题是,如果字典中的函数签名不正确,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
。我有两个问题:
- 为什么我没有收到任何错误消息?
- 我是否缺少一些会导致出现此错误的编译标志?
任何见识将不胜感激。谢谢!