首页 > 解决方案 > TypeScript Typed Function void Should Not Compile

问题描述

In the four functions below, the first two correctly return a number and the TypeScript compiler compiles them.

The third correctly causes a TypeScript compilation error but the fourth does not even though I expected it would?

// OK
let addNumbers: (a: number, b: number, c: number) => number = function (a, b, c) {
    return a + b + c;
};

// OK
let addNumbersTwo = function (a: number, b: number, c: number): number {
    return a + b + c;
};

// Correct compilation error
let addNumbersThree = function (a: number, b: number, c: number): void {
    return a + b + c;
};

// Should not compile? Should give same error as addNumbersThree above
let addNumbersFour: (a: number, b: number, c: number) => void = function (a, b, c) {
    return a + b + c;
};

TypeScript Playground example

标签: typescript

解决方案


那是因为(whatever) => whatever可分配给(whatever) => void.

由于 void 返回函数预计会丢弃它具有的任何不存在的返回值。

someVoidReturningFunction(args); // result doesn't get assigned or used.

someVoidReturningFunction实际上是否确实返回一个值并不重要,它只是被丢弃。

简而言之:给你的函数一个明确的返回值 void 表明消费代码不应该关心返回的结果

这是文档中的一个示例:

function callMeMaybe(callback: () => void) {
    callback();
}
let items = [1, 2];
callMeMaybe(() => items.push(3));

从技术上讲,items.push(3)将返回一个数字(新lengthitems)。但是,指定void回调实际上允许我们传递带有任何返回值的回调,并指示该返回值将被丢弃。


同样的推理也适用于缺失的论点。

let foo: ((a: number, b: number) => number) = () => 42; // compiles

因为您仍然可以调用foo(1, 2)并获取一个号码,即使这些变量在实践中未使用。


推荐阅读