【发布时间】:2019-01-20 19:17:07
【问题描述】:
我知道类型 'void' 在 typescript 上做了什么。但我遇到了以下代码。
function (obj: void){}
我在打字稿文档https://www.typescriptlang.org/docs/handbook/functions.html上看到了同样的情况@
类型“void”是什么意思 函数参数?
【问题讨论】:
标签: typescript
我知道类型 'void' 在 typescript 上做了什么。但我遇到了以下代码。
function (obj: void){}
我在打字稿文档https://www.typescriptlang.org/docs/handbook/functions.html上看到了同样的情况@
类型“void”是什么意思 函数参数?
【问题讨论】:
标签: typescript
void 作为this 类型很有用,因为它保证您不会使用this 参数。
function f(this: void, ...) {
// Can't use `this` in here.
}
在其他参数上,它……没那么有用。如果您关闭了--strictNullChecks,那么您仍然可以通过将null 或undefined 作为void 参数来调用该函数。如果你不这样做,那么你甚至不能调用这个函数,因为void 是无人居住的。
如果您之前没有看到将this 写成函数参数,我建议您阅读文档中的this section(完全是双关语)。
【讨论】:
(a: void) => void不带参数或any
简而言之,void 用于表示缺乏价值。您可以将其视为undefined 的另一种说法。
const foo: void = undefined;
当用作返回类型时,void 表示该函数不会显式返回任何内容。
function log(argument: any): void {
console.log(argument);
}
虽然在运行时 log 隐式返回 undefined,但 TypeScript 在概念上区分了 void 和 undefined。
function log(argument: any): void {
console.log(argument);
}
const foo: undefined = log('Hello'); // Error — "void" is not "undefined"
当用作this 类型时,void 表示在函数调用期间使用的this 将是默认的执行上下文——全局范围。在某些情况下它会有所帮助。创建scope-safe constructors 就是其中之一。
【讨论】: