Skip to main content

unified-signatures

Disallow two overloads that could be unified into one with a union or an optional/rest parameter.

🔒

ESLint 配置 中扩展"plugin:@typescript-eslint/strict" 可启用此规则。


函数重载签名是一种定义可以多种不同方式调用的函数的 TypeScript 方法。 重载签名会增加语法和理论上的膨胀,因此通常最好尽可能避免使用它们。 切换到联合类型和/或可选或剩余参数通常可以避免对重载签名的需要。

英:Function overload signatures are a TypeScript way to define a function that can be called in multiple very different ways. Overload signatures add syntax and theoretical bloat, so it's generally best to avoid using them when possible. Switching to union types and/or optional or rest parameters can often avoid the need for overload signatures.

此规则报告何时可以用单个函数签名替换函数重载签名。

英:This rule reports when function overload signatures can be replaced by a single function signature.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/unified-signatures": "error"
}
};
在线运行试试这个规则 ↗

示例

function x(x: number): void;
function x(x: string): void;
Open in Playground
function y(): void;
function y(...x: number[]): void;
Open in Playground

选项

ignoreDifferentlyNamedParameters

此规则与 ignoreDifferentlyNamedParameters 的代码示例:

英:Examples of code for this rule with ignoreDifferentlyNamedParameters:

function f(a: number): void;
function f(a: string): void;
Open in Playground

何时不使用它

这纯粹是一种风格规则,旨在帮助提高函数签名重载的可读性。 如果你不想始终保持它们彼此相邻且统一,则可以将其关闭。

英:This is purely a stylistic rule to help with readability of function signature overloads. You can turn it off if you don't want to consistently keep them next to each other and unified.

选项

该规则接受以下选项

type Options = [
{
/** Whether two parameters with different names at the same index should be considered different even if their types are the same. */
ignoreDifferentlyNamedParameters?: boolean;
},
];

const defaultOptions: Options = [{ ignoreDifferentlyNamedParameters: false }];

资源