跳到主要內容

no-invalid-void-type

禁止在一般或傳回類型之外使用 void 類型。

🔒

延伸 "plugin:@typescript-eslint/strict" ESLint 組態 啟用此規則。

TypeScript 中的 void 是指意在忽略的函式傳回。嘗試在傳回類型或一般類型參數之外使用 void 類型通常是程式設計錯誤的徵兆。void 即使正確使用,也可能會讓其他開發人員誤解。

void 類型表示無法與任何其他類型混用,除了能接受所有類型的 never。如果您認為需要它,那麼您大概想要 undefined 類型。

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-invalid-void-type": "error"
}
};

在操場中嘗試此規則 ↗

範例

type PossibleValues = string | number | void;
type MorePossibleValues = string | ((number & any) | (string | void));

function logSomething(thing: void) {}
function printArg<T = void>(arg: T) {}

logAndReturn<void>(undefined);

interface Interface {
lambda: () => void;
prop: void;
}

class MyClass {
private readonly propName: void;
}
在操場中開啟

選項

此規則接受下列選項

type Options = [
{
allowAsThisParameter?: boolean;
allowInGenericTypeArguments?: [string, ...string[]] | boolean;
},
];

const defaultOptions: Options = [
{ allowInGenericTypeArguments: true, allowAsThisParameter: false },
];

allowInGenericTypeArguments

此選項可讓您控制是否可將 void 用作泛型型別參數的有效值。

或者,您可以提供一組字串,將其白名單化,以接受 void 作為泛型型別參數。

此選項視為有效的任何型別都將與 void 一起視為聯合型別的一部分。

此選項預設為 true

{ allowInGenericTypeArguments: false } 中,下列模式視為警告

logAndReturn<void>(undefined);

let voidPromise: Promise<void> = new Promise<void>(() => {});
let voidMap: Map<string, void> = new Map<string, void>();
在操場中開啟

{ allowInGenericTypeArguments: ['Ex.Mx.Tx'] } 中,下列模式視為警告

logAndReturn<void>(undefined);

type NotAllowedVoid1 = Mx.Tx<void>;
type NotAllowedVoid2 = Tx<void>;
type NotAllowedVoid3 = Promise<void>;
在操場中開啟

{ allowInGenericTypeArguments: ['Ex.Mx.Tx'] } 中,下列模式未被視為警告

type AllowedVoid = Ex.Mx.Tx<void>;
type AllowedVoidUnion = void | Ex.Mx.Tx<void>;
在操場中開啟

allowAsThisParameter

此選項允許將函式設定為 void 時,指定為函式的 this 參數。此模式可用於明確標記未用 this 參數的函式型別。請參閱 TypeScript 文件,以取得更多資訊

此選項預設為 false

{ allowAsThisParameter: false } 中,下列模式視為警告,但是在 { allowAsThisParameter: true } 中則有效

function doThing(this: void) {}
class Example {
static helper(this: void) {}
callback(this: void) {}
}
在操場中開啟

何時不該使用

如果您不在乎 void 是否用於其他型別或無效的地方,則不需要此規則。

資源