TypeScript claims no error even if parameter has the wrong type

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:

  1. Why don't I get any error?
  2. Am I missing some compile flags that would cause this error to show up?

Any insight would be very appreciated. Thanks!

Mac*_*ora 6

没有问题,因为(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 类型行为和关系类型可分配性的细节。

  • @enanone 因为如果你输入 *one* 函数来 *明确地不返回某些内容*,如果它返回某些内容,则可能是一个错误。 (3认同)
  • 这是不同的事情,如果你声明函数返回`void`那么它应该返回`void`(所以没有返回)。这与可分配性无关。你只需声明不同的类型,然后你就真正返回了。所以在这个例子中 TS 应该阻止你。 (2认同)