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.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/unified-signatures": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

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

选项

该规则接受以下选项:

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;
/** Whether two overloads with different JSDoc comments should be considered different even if their parameter and return types are the same. */
ignoreOverloadsWithDifferentJSDoc?: boolean;
},
];

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

¥Options

ignoreDifferentlyNamedParameters

Whether two parameters with different names at the same index should be considered different even if their types are the same. Default: false.

带有 ignoreDifferentlyNamedParameters 的此规则的代码示例:

¥Examples of code for this rule with ignoreDifferentlyNamedParameters:

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

ignoreOverloadsWithDifferentJSDoc

Whether two overloads with different JSDoc comments should be considered different even if their parameter and return types are the same. Default: false.

带有 ignoreOverloadsWithDifferentJSDoc 的此规则的代码示例:

¥Examples of code for this rule with ignoreOverloadsWithDifferentJSDoc:

declare function f(x: string): void;
declare function f(x: boolean): void;
/**

* @deprecate
*/
declare function f(x: number): void;
/**

* @deprecate
*/
declare function f(x: null): void;
Open in Playground

何时不使用它

¥When Not To Use It

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

¥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.

相关

¥Related To

'## 资源'