启用 `strictNullChecks` 后,`void` 类型和 `undefined` 文字类型有什么区别?
With `strictNullChecks` enabled, what is the difference between the `void` type and `undefined` literal type?
启用 strictNullChecks
:
(u: undefined, v: void, n: null) => {
v = u;
u = v; // type error: Type 'void' is not assignable to type 'undefined'
v = n; // type error: Type 'null' is not assignable to type 'void'
}
我推测一定有一些 void
类型的值不是 undefined
类型的,但是启用了 strictNullChecks
我不知道有任何值。对于哪些值是正确的?
只有 2 种类型可以分配给 void
:undefined
和 null
。 Void 顾名思义,是任何东西的反义词,无,没有类型。
For which values is this true?
获取类型 void
的值的唯一方法是调用 void
返回函数:
function f() { }
let x = f();
请注意,由于通过 () => void
类型的变量为非 void
返回函数设置别名是合法的,因此以这种方式获得的 void
值可能 not 实际上是值 undefined
,因此是子类型关系。
启用 strictNullChecks
:
(u: undefined, v: void, n: null) => {
v = u;
u = v; // type error: Type 'void' is not assignable to type 'undefined'
v = n; // type error: Type 'null' is not assignable to type 'void'
}
我推测一定有一些 void
类型的值不是 undefined
类型的,但是启用了 strictNullChecks
我不知道有任何值。对于哪些值是正确的?
只有 2 种类型可以分配给 void
:undefined
和 null
。 Void 顾名思义,是任何东西的反义词,无,没有类型。
For which values is this true?
获取类型 void
的值的唯一方法是调用 void
返回函数:
function f() { }
let x = f();
请注意,由于通过 () => void
类型的变量为非 void
返回函数设置别名是合法的,因此以这种方式获得的 void
值可能 not 实际上是值 undefined
,因此是子类型关系。