|
| 1 | +import type { TSESTree } from '@typescript-eslint/utils'; |
| 2 | +import type { RuleContext } from '@typescript-eslint/utils/ts-eslint'; |
| 3 | + |
| 4 | +import { AST_NODE_TYPES } from '@typescript-eslint/utils'; |
| 5 | + |
| 6 | +import { getStaticMemberAccessValue } from './misc'; |
| 7 | + |
| 8 | +/** |
| 9 | + * @return `true` if the function or method node has overload signatures. |
| 10 | + */ |
| 11 | +export function hasOverloadSignatures( |
| 12 | + node: TSESTree.FunctionDeclaration | TSESTree.MethodDefinition, |
| 13 | + context: RuleContext<string, unknown[]>, |
| 14 | +): boolean { |
| 15 | + // `export default function () {}` |
| 16 | + if (node.parent.type === AST_NODE_TYPES.ExportDefaultDeclaration) { |
| 17 | + return node.parent.parent.body.some(member => { |
| 18 | + return ( |
| 19 | + member.type === AST_NODE_TYPES.ExportDefaultDeclaration && |
| 20 | + member.declaration.type === AST_NODE_TYPES.TSDeclareFunction |
| 21 | + ); |
| 22 | + }); |
| 23 | + } |
| 24 | + |
| 25 | + // `export function f() {}` |
| 26 | + if (node.parent.type === AST_NODE_TYPES.ExportNamedDeclaration) { |
| 27 | + return node.parent.parent.body.some(member => { |
| 28 | + return ( |
| 29 | + member.type === AST_NODE_TYPES.ExportNamedDeclaration && |
| 30 | + member.declaration?.type === AST_NODE_TYPES.TSDeclareFunction && |
| 31 | + getFunctionDeclarationName(member.declaration, context) === |
| 32 | + getFunctionDeclarationName(node, context) |
| 33 | + ); |
| 34 | + }); |
| 35 | + } |
| 36 | + |
| 37 | + // either: |
| 38 | + // - `function f() {}` |
| 39 | + // - `class T { foo() {} }` |
| 40 | + |
| 41 | + const nodeKey = getFunctionDeclarationName(node, context); |
| 42 | + |
| 43 | + return node.parent.body.some(member => { |
| 44 | + return ( |
| 45 | + (member.type === AST_NODE_TYPES.TSDeclareFunction || |
| 46 | + (member.type === AST_NODE_TYPES.MethodDefinition && |
| 47 | + member.value.body == null)) && |
| 48 | + nodeKey === getFunctionDeclarationName(member, context) |
| 49 | + ); |
| 50 | + }); |
| 51 | +} |
| 52 | + |
| 53 | +function getFunctionDeclarationName( |
| 54 | + node: |
| 55 | + | TSESTree.FunctionDeclaration |
| 56 | + | TSESTree.MethodDefinition |
| 57 | + | TSESTree.TSDeclareFunction, |
| 58 | + context: RuleContext<string, unknown[]>, |
| 59 | +): string | symbol | undefined { |
| 60 | + if ( |
| 61 | + node.type === AST_NODE_TYPES.FunctionDeclaration || |
| 62 | + node.type === AST_NODE_TYPES.TSDeclareFunction |
| 63 | + ) { |
| 64 | + // For a `FunctionDeclaration` or `TSDeclareFunction` this may be `null` if |
| 65 | + // and only if the parent is an `ExportDefaultDeclaration`. |
| 66 | + // |
| 67 | + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 68 | + return node.id!.name; |
| 69 | + } |
| 70 | + |
| 71 | + return getStaticMemberAccessValue(node, context); |
| 72 | +} |
0 commit comments