即使参数的类型错误,TypeScript也不会声明任何错误

我有一个将字典作为第一个参数的函数。该字典具有字符串作为键,并具有值的功能。问题是,如果字典中的函数签名不正确,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。我有两个问题:

  1. 为什么我没有收到任何错误消息?
  2. 我是否缺少一些会导致出现此错误的编译标志?

任何见识将不胜感激。谢谢!

pl3000 回答:即使参数的类型错误,TypeScript也不会声明任何错误

没有问题,因为(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 

这个事实对于程序流来说是完全可以的。如果您的界面说-我需要一个不返回的函数,那么如果我传递了一个可以返回某些东西的函数,则完全可以,因为我永远不会使用此返回数据。它是安全类型,无需担心。

有关功能可分配性的更多详细信息-Comparing two functions。还有有关TypeScript类型行为和关系的更多详细信息-types assignability

本文链接:https://www.f2er.com/2992406.html

大家都在问