Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(generic-spacing): improve cases
  • Loading branch information
antfu committed Nov 2, 2022
1 parent e13613f commit ff6a1fa
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 11 deletions.
12 changes: 12 additions & 0 deletions packages/eslint-plugin-antfu/src/rules/generic-spacing.test.ts
Expand Up @@ -13,12 +13,24 @@ type Foo<
`function foo<
T
>() {}`,
'const foo = <T>(name: T) => name',
`interface Log {
foo<T>(name: T): void
}`,
`interface Log {
<T>(name: T): void
}`,
]
const invalids = [
['type Foo<T=true> = T', 'type Foo<T = true> = T'],
['type Foo<T,K> = T', 'type Foo<T, K> = T'],
['type Foo<T=false,K=1|2> = T', 'type Foo<T = false, K = 1|2> = T', 3],
['function foo <T>() {}', 'function foo<T>() {}'],
[`interface Log {
foo <T>(name: T): void
}`, `interface Log {
foo<T>(name: T): void
}`],
] as const

it('runs', () => {
Expand Down
24 changes: 13 additions & 11 deletions packages/eslint-plugin-antfu/src/rules/generic-spacing.ts
Expand Up @@ -23,17 +23,19 @@ export default createEslintRule<Options, MessageIds>({
const sourceCode = context.getSourceCode()
return {
TSTypeParameterDeclaration: (node) => {
const pre = sourceCode.text.slice(0, node.range[0])
const preSpace = pre.match(/(\s+)$/)?.[0]
// strip space before <T>
if (preSpace && preSpace.length) {
context.report({
node,
messageId: 'genericSpacingMismatch',
*fix(fixer) {
yield fixer.replaceTextRange([node.range[0] - preSpace.length, node.range[0]], '')
},
})
if (!['TSCallSignatureDeclaration', 'ArrowFunctionExpression'].includes(node.parent.type)) {
const pre = sourceCode.text.slice(0, node.range[0])
const preSpace = pre.match(/(\s+)$/)?.[0]
// strip space before <T>
if (preSpace && preSpace.length) {
context.report({
node,
messageId: 'genericSpacingMismatch',
*fix(fixer) {
yield fixer.replaceTextRange([node.range[0] - preSpace.length, node.range[0]], '')
},
})
}
}

// add space between <T,K>
Expand Down

0 comments on commit ff6a1fa

Please sign in to comment.