typescript - 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;
};
解决方案
那是因为(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)
将返回一个数字(新length
的items
)。但是,指定void
回调实际上允许我们传递带有任何返回值的回调,并指示该返回值将被丢弃。
同样的推理也适用于缺失的论点。
let foo: ((a: number, b: number) => number) = () => 42; // compiles
因为您仍然可以调用foo(1, 2)
并获取一个号码,即使这些变量在实践中未使用。
推荐阅读
- google-sheets - 在 Google 表格中从姓氏中拆分名字
- node.js - 如何让我的函数仅在异步调用完成后返回 200?
- r - 为R中的每个ID按升序生成时间戳
- java - 如何以时间戳/日期时间格式在 Scala 中获取当前时间,以便将其存储在 PG 表中
- if-statement - Airtable If 语句输出 NaN
- jquery - 获取最后 4 条记录而不获取 4 条记录数据 laravel
- javascript - 这是 IE 11 中的错误吗?
- r - R ggplot 在 geom_rect 中添加注释
- sql - SQL 查询 User.first_name OR User.last_name OR 两者?
- php - PHP 将文本转换为查询