在打字稿中无效。为什么我从 console.log 得到结果?

void in TypeScript. Why do I get the result from the console.log?

let foo: void;
foo = 2;

没听懂,求解释。当我们用 LET 键入 void 时 - 好的,我明白了。

但是,当我们在这里输入例如:

function test(message): void {
  console.log(message);
}

test("hi");

无论如何我都会得到“嗨”。为什么?

我有点困惑想理解

I didn't get, explain to me please. When we type void with LET - ok, I got

但是如果我在脑海中正确地解析它,那么问题的后半部分将 void 显示为函数的 return 类型(在这种情况下,什么都没有),而问题的前半部分显示一个 void 变量,Typescript 只允许 nullundefined 作为赋值。

后半部分工作正常,因为该函数不会尝试 return 任何东西。它不接受“void”作为参数。 message 类型是无类型的,因此实际上任何对象都可以进入。

函数的最后一个类型用于定义其return的类型。

您可能会问,为什么它有效?

function test(msg: string): void {
  console.log(msg);
}

因为它return什么都没有。

let myVar: void = test("hello!");
console.log(myVar);

当你尝试的时候,myVar 会returnundefined,因为函数本身return什么都没有。与 this Typescript example.

相同
let unusable: void = undefined;

那么return是什么意思呢? Return 是 return 从函数中编辑的数据。示例:

function idk(): string {
   return "Hello World!";
}

然后,当我执行它时,它执行 return 字符串。

let myVar: string = idk();
console.log(myVar);

通过 MDN 查看此 return documentation