Skip to content

Commit

Permalink
feat(generic-spacing): remove spaces in type param instantiation (#677)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ericlm authored Feb 8, 2025
1 parent 21704b6 commit 2a29e28
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ run({
name: 'type-generic-spacing',
rule,
valid: [
'const foo: Array<number> = []',
'type Foo<T = true> = T',
'type Foo<T extends true = true> = T',
'type Foo<T = (true)> = T',
Expand Down Expand Up @@ -40,6 +41,9 @@ run({
`const toSortedImplementation = Array.prototype.toSorted || function <T>(name: T): void {}`,
],
invalid: ([
['const val: Set< string> = new Set()', 'const val: Set<string> = new Set()'],
['const val: Array< number > = []', 'const val: Array<number> = []', 2],
['const val = callback< string >(() => \'foo\')', 'const val = callback<string>(() => \'foo\')', 2],
['type Foo< T> = T', 'type Foo<T> = T'],
['type Foo<T > = T', 'type Foo<T> = T'],
['type Foo< T > = T', 'type Foo<T> = T', 2],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,48 @@ export default createRule<RuleOptions, MessageIds>({
const sourceCode = context.sourceCode

return {
TSTypeParameterInstantiation: (node) => {
const params = node.params

const openToken = sourceCode.getTokenBefore(params[0])
const firstToken = openToken ? sourceCode.getTokenAfter(openToken) : null

const closeToken = sourceCode.getTokenAfter(params[params.length - 1])
const lastToken = closeToken ? sourceCode.getTokenBefore(closeToken) : null

// remove spaces between "<" and the first type parameter
if (openToken && firstToken) {
const textBetween = sourceCode.text.slice(openToken.range[1], firstToken.range[0])

// raise error only if there is no newline
if (/\s/.test(textBetween) && !/^[\r\n]/.test(textBetween)) {
context.report({
node,
messageId: 'genericSpacingMismatch',
*fix(fixer) {
yield fixer.replaceTextRange([openToken.range[1], firstToken.range[0]], '')
},
})
}
}

// remove spaces between the last type parameter and ">"
if (closeToken && lastToken) {
const textBetween = sourceCode.text.slice(lastToken.range[1], closeToken.range[0])

// raise error only if there is no newline
if (/\s/.test(textBetween) && !/^[\r\n]/.test(textBetween)) {
context.report({
node,
messageId: 'genericSpacingMismatch',
*fix(fixer) {
yield fixer.replaceTextRange([lastToken.range[1], closeToken.range[0]], '')
},
})
}
}
},

TSTypeParameterDeclaration: (node) => {
if (!PRESERVE_PREFIX_SPACE_BEFORE_GENERIC.has(node.parent.type)) {
const pre = sourceCode.text.slice(0, node.range[0])
Expand Down

0 comments on commit 2a29e28

Please sign in to comment.