[英]TypeScript claims no error even if parameter has the wrong type
I have a function that takes a dictionary as the first argument.我有一个将字典作为第一个参数的函数。 This dictionary has string as keys, and functions as values.该字典以字符串为键,以函数为值。 The problem is that, if a function in the dictionary has a bad signature, TypeScript does not complain!问题是,如果字典中的函数签名错误,TypeScript 不会抱怨!
A piece of code is worth 1000 words.一段代码值 1000 字。 Here's my main.ts
:这是我的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
I compile it with tsc main.ts
, and I get no error whatsoever.我用tsc main.ts
编译它,我没有得到任何错误。 tsc --version
prints Version 3.7.2
. tsc --version
打印Version 3.7.2
。 I have two questions:我有两个问题:
Any insight would be very appreciated.任何见解将不胜感激。 Thanks!谢谢!
There is no issue because (x: number) => void
is assignable to (x: number) => number
.没有问题,因为(x: number) => void
可分配给(x: number) => number
。 And here is a prove of that:这是一个证明:
type F = (x: number) => void
type Z = (x: number) => number
type ZextendsF = Z extends F ? true : false // evaluate to true
And this fact is totally fine for the program flow.这个事实对于程序流程来说是完全没问题的。 If your interface says - I require a function which does not return, then If I pass a function which return something, its fully ok, as I will never use this return data.如果你的界面说 - 我需要一个不返回的函数,那么如果我传递一个返回某些东西的函数,它完全可以,因为我永远不会使用这个返回数据。 It is type safe and nothing to worry about.它是类型安全的,无需担心。
More details about functions assignability - Comparing two functions .有关函数可分配性的更多详细信息 - 比较两个函数。 Also more details about TypeScript types behavior and relation - types assignability .还有更多关于 TypeScript 类型行为和关系类型可分配性的细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.