ena*_*one 4 javascript return-type typescript tsc
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!
A piece of code is worth 1000 words. Here's my 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
Run Code Online (Sandbox Code Playgroud)
I compile it with tsc main.ts, and I get no error whatsoever. tsc --version prints Version 3.7.2. I have two questions:
Any insight would be very appreciated. Thanks!
没有问题,因为(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
Run Code Online (Sandbox Code Playgroud)
这个事实对于程序流程来说是完全没问题的。如果你的界面说 - 我需要一个不返回的函数,那么如果我传递一个返回某些东西的函数,它完全可以,因为我永远不会使用这个返回数据。它是类型安全的,无需担心。
有关函数可分配性的更多详细信息 -比较两个函数。还有更多关于 TypeScript 类型行为和关系类型可分配性的细节。
| 归档时间: |
|
| 查看次数: |
2141 次 |
| 最近记录: |