TypeScript并不总是强制执行功能签名

时间:2017-06-09 18:34:09

标签: typescript

假设我创建了一个键入的对象,其中键是一个字符串,该值是一个接收数字并且不返回任何内容的函数:

SELECT 
batch, count(SUserSessionID)  
FROM  
test.transactions  
WHERE batch between 2011 and 2017 
group by batch;

当我为这个对象分配函数时,似乎没有强制执行类型检查:

let funcMap: { [id: string]: (num: number) => void };

但是,在调用函数时强制执行类型检查:

funcMap = {
  // This is OK, as expected

  'one': (num: number) => { },

  // I would expect this be an error because there is no string function parameter

  'two': () => { },

  // I would expect this be an error because the function returns a number

  'three': () => 0
};

这是另一个例子:

// This is OK, as expected

funcMap['two'](0);

// This is an error, as expected

funcMap['two']();

这种行为是故意的吗?

1 个答案:

答案 0 :(得分:2)

是的,这种行为是有意的。

这样想:函数是否接受一些无参数是否重要?从来电者的角度来看,它没有什么区别:

type INumFunc = (num: number) => any;

const a = (num: number) => { ... };
const b = () => { ... };

(<any>a)(num); // as intended
(<any>b)(num); // no negative side effect since `b` doesn't use the number

同样的概念适用于返回类型。当调用者期望函数返回void时,返回值保持未使用状态。那么,为什么要关心?