Skip to content

noConfusingVoidType

诊断类别:lint/suspicious/noConfusingVoidType

¥Diagnostic Category: lint/suspicious/noConfusingVoidType

自从:v1.2.0

¥Since: v1.2.0

来源:

¥Sources:

禁止在通用或返回类型之外使用 void 类型。

¥Disallow void type outside of generic or return types.

TypeScript 中的 void 指的是一个应该被忽略的函数返回。尝试在返回类型或类型参数之外使用 void 类型通常是程序员错误的标志。即使使用正确,void 也会误导其他开发者。

¥void in TypeScript refers to a function return that is meant to be ignored. Attempting to use a void type outside of a return type or a type parameter is often a sign of programmer error. void can also be misleading for other developers even if used correctly.

void 类型意味着不能与除 never 之外的任何其他类型混合,never 接受所有类型。如果你认为需要这个,那么你可能想要 undefined 类型。

¥The void type means cannot be mixed with any other types, other than never, which accepts all types. If you think you need this then you probably want the undefined type instead.

代码操作建议使用 undefined 而不是 void。这是不安全的,因为不能将 void 类型的变量分配给 undefined 类型的变量。

¥The code action suggests using undefined instead of void. It is unsafe because a variable with the void type cannot be asigned to a variable with the undefined type.

¥Examples

¥Invalid

let foo: void;
code-block.ts:1:10 lint/suspicious/noConfusingVoidType  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

void is confusing outside a return type or a type parameter.

> 1 │ let foo: void;
^^^^
2 │

Unsafe fix: Use undefined instead.

1 - let·foo:·void;
1+ let·foo:·undefined;
2 2

function logSomething(thing: void) {}
code-block.ts:1:30 lint/suspicious/noConfusingVoidType  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

void is confusing outside a return type or a type parameter.

> 1 │ function logSomething(thing: void) {}
^^^^
2 │

Unsafe fix: Use undefined instead.

1 - function·logSomething(thing:·void)·{}
1+ function·logSomething(thing:·undefined)·{}
2 2

interface Interface {
prop: void;
}
code-block.ts:2:11 lint/suspicious/noConfusingVoidType  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

void is confusing outside a return type or a type parameter.

1 │ interface Interface {
> 2 │ prop: void;
^^^^
3 │ }
4 │

Unsafe fix: Use undefined instead.

1 1 interface Interface {
2 - ····prop:·void;
2+ ····prop:·undefined;
3 3 }
4 4

type PossibleValues = number | void;
code-block.ts:1:32 lint/suspicious/noConfusingVoidType  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

void is confusing inside a union type.

> 1 │ type PossibleValues = number | void;
^^^^
2 │

Unsafe fix: Use undefined instead.

1 - type·PossibleValues·=·number·|·void;
1+ type·PossibleValues·=·number·|·undefined;
2 2

¥Valid

function foo(): void {};
function doSomething(this: void) {}
function printArg<T = void>(arg: T) {}

¥Related links