【发布时间】:2020-03-27 05:09:17
【问题描述】:
我有一个将字典作为第一个参数的函数。这个字典有字符串作为键,函数作为值。问题是,如果字典中的函数签名错误,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。我有两个问题:
- 为什么我没有收到任何错误消息?
- 我是否遗漏了一些会导致出现此错误的编译标志?
任何见解将不胜感激。谢谢!
【问题讨论】:
标签: javascript typescript return-type tsc