简体   繁体   中英

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!

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

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!

There is no issue because (x: number) => void is assignable to (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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM