Skip to content

Commit 243fb5f

Browse files
authored
chore: enable prefer-template (#9544)
* prefer-template * review * cleanup * minor cleanup
1 parent a4acc2b commit 243fb5f

File tree

22 files changed

+62
-73
lines changed

22 files changed

+62
-73
lines changed

eslint.config.mjs

+1
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,7 @@ export default tseslint.config(
223223
'prefer-object-has-own': 'error',
224224
'prefer-object-spread': 'error',
225225
'prefer-rest-params': 'error',
226+
'prefer-template': 'error',
226227
radix: 'error',
227228

228229
//

packages/ast-spec/tests/util/serialize-error.ts

+9-12
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,13 @@ export function serializeError(error: unknown, contents: string): unknown {
1313
location: { start, end },
1414
} = error;
1515

16-
return (
17-
name +
18-
'\n' +
19-
codeFrameColumns(
20-
contents,
21-
{
22-
start: { line: start.line, column: start.column + 1 },
23-
end: { line: end.line, column: end.column + 1 },
24-
},
25-
{ highlightCode: false, message },
26-
)
27-
);
16+
return `${name}
17+
${codeFrameColumns(
18+
contents,
19+
{
20+
start: { line: start.line, column: start.column + 1 },
21+
end: { line: end.line, column: end.column + 1 },
22+
},
23+
{ highlightCode: false, message },
24+
)}`;
2825
}

packages/ast-spec/tests/util/snapshot-diff.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ export function snapshotDiff(
5757
throw new Error('Unexpected null when diffing snapshots.');
5858
}
5959

60-
return 'Snapshot Diff:\n' + difference;
60+
return `Snapshot Diff:\n${difference}`;
6161
}
6262

6363
// https://github.com/facebook/jest/blob/a293b75310cfc209713df1d34d243eb258995316/packages/jest-diff/src/constants.ts#L8

packages/eslint-plugin-internal/src/rules/plugin-test-formatting.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ function getExpectedIndentForNode(
6363
}
6464
function doIndent(line: string, indent: number): string {
6565
for (let i = 0; i < indent; i += 1) {
66-
line = ' ' + line;
66+
line = ` ${line}`;
6767
}
6868
return line;
6969
}

packages/eslint-plugin/src/rules/consistent-generic-constructors.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ export default createRule<Options, MessageIds>({
103103
fixer.remove(typeArguments),
104104
fixer.insertTextAfter(
105105
getIDToAttachAnnotation(),
106-
': ' + typeAnnotation,
106+
`: ${typeAnnotation}`,
107107
),
108108
];
109109
},

packages/eslint-plugin/src/rules/no-floating-promises.ts

+2-4
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,8 @@ export default createRule<Options, MessageId>({
6767
floatingFixAwait: 'Add await operator.',
6868
floatingVoid: messageBaseVoid,
6969
floatingFixVoid: 'Add void operator to ignore.',
70-
floatingUselessRejectionHandler:
71-
messageBase + ' ' + messageRejectionHandler,
72-
floatingUselessRejectionHandlerVoid:
73-
messageBaseVoid + ' ' + messageRejectionHandler,
70+
floatingUselessRejectionHandler: `${messageBase} ${messageRejectionHandler}`,
71+
floatingUselessRejectionHandlerVoid: `${messageBaseVoid} ${messageRejectionHandler}`,
7472
floatingPromiseArray: messagePromiseArray,
7573
floatingPromiseArrayVoid: messagePromiseArrayVoid,
7674
},

packages/eslint-plugin/src/rules/no-unsafe-assignment.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -324,8 +324,8 @@ export default createRule({
324324
): Readonly<Record<string, unknown>> | undefined {
325325
if (receiverType) {
326326
return {
327-
sender: '`' + checker.typeToString(senderType) + '`',
328-
receiver: '`' + checker.typeToString(receiverType) + '`',
327+
sender: `\`${checker.typeToString(senderType)}\``,
328+
receiver: `\`${checker.typeToString(receiverType)}\``,
329329
};
330330
}
331331
return {

packages/eslint-plugin/src/rules/prefer-function-type.ts

+7-9
Original file line numberDiff line numberDiff line change
@@ -142,15 +142,13 @@ export default createRule({
142142
node.type === AST_NODE_TYPES.TSInterfaceDeclaration &&
143143
isParentExported
144144
) {
145-
const commentsText = comments.reduce((text, comment) => {
146-
return (
147-
text +
148-
(comment.type === AST_TOKEN_TYPES.Line
149-
? `//${comment.value}`
150-
: `/*${comment.value}*/`) +
151-
'\n'
152-
);
153-
}, '');
145+
const commentsText = comments
146+
.map(({ type, value }) =>
147+
type === AST_TOKEN_TYPES.Line
148+
? `//${value}\n`
149+
: `/*${value}*/\n`,
150+
)
151+
.join('');
154152
// comments should move before export and not between export and interface declaration
155153
fixes.push(fixer.insertTextBefore(node.parent, commentsText));
156154
} else {

packages/eslint-plugin/src/rules/prefer-optional-chain-utils/analyzeChain.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,7 @@ function getReportDescriptor(
376376
if (lastOperand.isYoda) {
377377
const unaryOperator =
378378
lastOperand.node.right.type === AST_NODE_TYPES.UnaryExpression
379-
? lastOperand.node.right.operator + ' '
379+
? `${lastOperand.node.right.operator} `
380380
: '';
381381

382382
return {
@@ -386,7 +386,7 @@ function getReportDescriptor(
386386
}
387387
const unaryOperator =
388388
lastOperand.node.left.type === AST_NODE_TYPES.UnaryExpression
389-
? lastOperand.node.left.operator + ' '
389+
? `${lastOperand.node.left.operator} `
390390
: '';
391391
return {
392392
left: unaryOperator + newCode,

packages/eslint-plugin/src/rules/unbound-method.ts

+1-4
Original file line numberDiff line numberDiff line change
@@ -113,10 +113,7 @@ export default createRule<Options, MessageIds>({
113113
},
114114
messages: {
115115
unbound: BASE_MESSAGE,
116-
unboundWithoutThisAnnotation:
117-
BASE_MESSAGE +
118-
'\n' +
119-
'If your function does not access `this`, you can annotate it with `this: void`, or consider using an arrow function instead.',
116+
unboundWithoutThisAnnotation: `${BASE_MESSAGE}\nIf your function does not access \`this\`, you can annotate it with \`this: void\`, or consider using an arrow function instead.`,
120117
},
121118
schema: [
122119
{

packages/eslint-plugin/src/rules/use-unknown-in-catch-callback-variable.ts

+7-8
Original file line numberDiff line numberDiff line change
@@ -41,14 +41,13 @@ export default createRule<[], MessageIds>({
4141
type: 'suggestion',
4242
messages: {
4343
useUnknown: useUnknownMessageBase,
44-
useUnknownArrayDestructuringPattern:
45-
useUnknownMessageBase + ' The thrown error may not be iterable.',
46-
useUnknownObjectDestructuringPattern:
47-
useUnknownMessageBase +
48-
' The thrown error may be nullable, or may not have the expected shape.',
49-
useUnknownSpreadArgs:
50-
useUnknownMessageBase +
51-
' The argument list may contain a handler that does not use `unknown` for the catch callback variable.',
44+
useUnknownArrayDestructuringPattern: `${useUnknownMessageBase} The thrown error may not be iterable.`,
45+
useUnknownObjectDestructuringPattern: `${
46+
useUnknownMessageBase
47+
} The thrown error may be nullable, or may not have the expected shape.`,
48+
useUnknownSpreadArgs: `${
49+
useUnknownMessageBase
50+
} The argument list may contain a handler that does not use \`unknown\` for the catch callback variable.`,
5251
addUnknownTypeAnnotationSuggestion:
5352
'Add an explicit `: unknown` type annotation to the catch variable.',
5453
addUnknownRestTypeAnnotationSuggestion:

packages/eslint-plugin/tests/docs.test.ts

+14-12
Original file line numberDiff line numberDiff line change
@@ -83,11 +83,11 @@ function renderLintResults(code: string, errors: Linter.LintMessage[]): string {
8383
? Math.max(1, endColumn - startColumn)
8484
: line.length - startColumn,
8585
);
86-
const squiggleWithIndent = ' '.repeat(startColumn) + squiggle + ' ';
86+
const squiggleWithIndent = `${' '.repeat(startColumn)}${squiggle} `;
8787
const errorMessageIndent = ' '.repeat(squiggleWithIndent.length);
8888
output.push(
8989
squiggleWithIndent +
90-
error.message.split('\n').join('\n' + errorMessageIndent),
90+
error.message.replaceAll('\n', `\n${errorMessageIndent}`),
9191
);
9292
} else if (i === endLine) {
9393
output.push('~'.repeat(endColumn));
@@ -97,7 +97,7 @@ function renderLintResults(code: string, errors: Linter.LintMessage[]): string {
9797
}
9898
}
9999

100-
return output.join('\n').trim() + '\n';
100+
return `${output.join('\n').trim()}\n`;
101101
}
102102

103103
const linter = new Linter({ configType: 'eslintrc' });
@@ -484,27 +484,28 @@ describe('Validating rule docs', () => {
484484
if (token.meta?.includes('skipValidation')) {
485485
assert.ok(
486486
messages.length === 0,
487-
'Expected not to contain lint errors (with skipValidation):\n' +
488-
token.value,
487+
`Expected not to contain lint errors (with skipValidation):
488+
${token.value}`,
489489
);
490490
} else {
491491
assert.ok(
492492
messages.length > 0,
493-
'Expected to contain at least 1 lint error:\n' + token.value,
493+
`Expected to contain at least 1 lint error:\n${token.value}`,
494494
);
495495
}
496496
} else {
497497
testCaption.push('Correct');
498498
if (token.meta?.includes('skipValidation')) {
499499
assert.ok(
500500
messages.length > 0,
501-
'Expected to contain at least 1 lint error (with skipValidation):\n' +
502-
token.value,
501+
`Expected to contain at least 1 lint error (with skipValidation):\n${
502+
token.value
503+
}`,
503504
);
504505
} else {
505506
assert.ok(
506507
messages.length === 0,
507-
'Expected not to contain lint errors:\n' + token.value,
508+
`Expected not to contain lint errors:\n${token.value}`,
508509
);
509510
}
510511
}
@@ -514,9 +515,10 @@ describe('Validating rule docs', () => {
514515
}
515516

516517
expect(
517-
testCaption.filter(Boolean).join('\n') +
518-
'\n\n' +
519-
renderLintResults(token.value, messages),
518+
`${testCaption.filter(Boolean).join('\n')}\n\n${renderLintResults(
519+
token.value,
520+
messages,
521+
)}`,
520522
).toMatchSpecificSnapshot(
521523
path.join(eslintOutputSnapshotFolder, `${ruleName}.shot`),
522524
);

packages/eslint-plugin/tools/generate-breaking-changes.mts

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ async function main(): Promise<void> {
3737
// But this is an internal-only script and it's the easiest way to convert
3838
// the JS raw text into a runtime object. 🤷
3939
let oldRulesObject!: { rules: TypeScriptESLintRules };
40-
eval('oldRulesObject = ' + oldObjectText);
40+
eval(`oldRulesObject = ${oldObjectText}`);
4141
const oldRuleNames = new Set(Object.keys(oldRulesObject.rules));
4242

4343
// 3. Get the keys that exist in (1) (new version) and not (2) (old version)

packages/parser/tests/test-utils/test-utils.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,6 @@ export function formatSnapshotName(
8787
fileExtension = '.js',
8888
): string {
8989
return `fixtures/${filename
90-
.replace(fixturesDir + '/', '')
90+
.replace(`${fixturesDir}/`, '')
9191
.replace(fileExtension, '')}`;
9292
}

packages/typescript-estree/tests/test-utils/test-utils.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ export function formatSnapshotName(
5858
fileExtension = '.js',
5959
): string {
6060
return `fixtures/${filename
61-
.replace(fixturesDir + '/', '')
61+
.replace(`${fixturesDir}/`, '')
6262
.replace(fileExtension, '')}`;
6363
}
6464

packages/utils/tests/eslint-utils/getParserServices.test.ts

+2-3
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,8 @@ const baseErrorRegex = (parser?: string): RegExp =>
3333
new RegExp(requiresParserServicesMessageTemplate(parser));
3434
const unknownParserErrorRegex = (parser?: string): RegExp =>
3535
new RegExp(
36-
requiresParserServicesMessageTemplate(parser) +
37-
'\n' +
38-
'Note: detected a parser other than @typescript-eslint/parser. Make sure the parser is configured to forward "parserOptions.project" to @typescript-eslint/parser.',
36+
`${requiresParserServicesMessageTemplate(parser)}
37+
Note: detected a parser other than @typescript-eslint/parser. Make sure the parser is configured to forward "parserOptions.project" to @typescript-eslint/parser.`,
3938
);
4039

4140
describe('getParserServices', () => {

packages/website-eslint/build.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,14 @@ function makeFilter(filePath: string[] | string): { filter: RegExp } {
2323
const norm = paths.map(item =>
2424
normalizePath(item).replace(/\//g, '[\\\\/]').replace(/\./g, '\\.'),
2525
);
26-
return { filter: new RegExp('(' + norm.join('|') + ')$') };
26+
return { filter: new RegExp(`(${norm.join('|')})$`) };
2727
}
2828

2929
function createResolve(
3030
targetPath: string,
3131
join: string,
3232
): esbuild.OnResolveResult {
33-
const resolvedPackage = requireResolved(targetPath + '/package.json');
33+
const resolvedPackage = requireResolved(`${targetPath}/package.json`);
3434
return {
3535
path: path.join(resolvedPackage, '../src/', join),
3636
};

packages/website-eslint/src/mock/assert.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ class AssertionError extends Error {
5151
typeof stackStartFunction === 'function'
5252
? stackStartFunction.name
5353
: stackStartFunction.toString();
54-
const idx = out.indexOf('\n' + fn_name);
54+
const idx = out.indexOf(`\n${fn_name}`);
5555
if (idx >= 0) {
5656
// once we have located the function frame
5757
// we need to strip out everything before it (and its line)

packages/website-eslint/src/mock/path.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ export function resolve(...args) {
7373
continue;
7474
}
7575

76-
resolvedPath = path + '/' + resolvedPath;
76+
resolvedPath = `${path}/${resolvedPath}`;
7777
resolvedAbsolute = path.charAt(0) === '/';
7878
}
7979

packages/website/src/components/editor/createProvideTwoslashInlay.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ export function createTwoslashInlayProvider(
6868
const inspectionOff = model.getOffsetAt(inspectionPos);
6969

7070
const hint = await (worker.getQuickInfoAtPosition(
71-
'file://' + model.uri.path,
71+
`file://${model.uri.path}`,
7272
inspectionOff,
7373
) as Promise<ts.QuickInfo | undefined>);
7474
if (!hint?.displayParts) {
@@ -80,7 +80,7 @@ export function createTwoslashInlayProvider(
8080
.join('')
8181
.replace(/\r?\n\s*/g, ' ');
8282
if (text.length > 120) {
83-
text = text.slice(0, 119) + '...';
83+
text = `${text.slice(0, 119)}...`;
8484
}
8585

8686
return {

packages/website/src/components/editor/useSandboxServices.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ export const useSandboxServices = (
103103
if (worker.getLibFiles) {
104104
const libs = await worker.getLibFiles();
105105
for (const [key, value] of Object.entries(libs)) {
106-
system.writeFile('/' + key, value);
106+
system.writeFile(`/${key}`, value);
107107
}
108108
}
109109

packages/website/tools/generate-website-dts.ts

+2-4
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,8 @@ function replaceImports(text: string, from: string, to: string): string {
5252
function injectImports(text: string, from: string, safeName: string): string {
5353
const regex = new RegExp(`import\\(["']${from}["']\\)`, 'g');
5454
if (regex.test(text)) {
55-
return (
56-
`import type * as ${safeName} from '${from}';\n` +
57-
text.replace(regex, safeName)
58-
);
55+
return `import type * as ${safeName} from '${from}';
56+
${text.replace(regex, safeName)}`;
5957
}
6058
return text;
6159
}

0 commit comments

Comments
 (0)