Skip to content

Commit

Permalink
feat(generic-spacing): remove space before generic
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Oct 31, 2022
1 parent 254f819 commit e111029
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
Expand Up @@ -4,17 +4,21 @@ import rule, { RULE_NAME } from './generic-spacing'

const valids = [
'type Foo<T = true> = T',
'type Foo<T extends true = true> = T',
`
type Foo<
T = true,
K = false
> = T`,
'type Foo<T extends true = true> = T',
`function foo<
T
>() {}`,
]
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>() {}'],
] as const

it('runs', () => {
Expand Down
15 changes: 15 additions & 0 deletions packages/eslint-plugin-antfu/src/rules/generic-spacing.ts
Expand Up @@ -23,6 +23,20 @@ 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]], '')
},
})
}

// add space between <T,K>
const params = node.params
for (let i = 1; i < params.length; i++) {
const prev = params[i - 1]
Expand All @@ -45,6 +59,7 @@ export default createEslintRule<Options, MessageIds>({
}
}
},
// add space around = in type Foo<T = true>
TSTypeParameter: (node) => {
if (!node.default)
return
Expand Down

2 comments on commit e111029

@mino01x
Copy link

@mino01x mino01x commented on e111029 Nov 2, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe has problems in some cases

const foo = <T>(name: T) => name

interface Log {
  <T>(name: T): void
}

@antfu
Copy link
Owner Author

@antfu antfu commented on e111029 Nov 2, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. Fixed.

Please sign in to comment.