Skip to content

Commit 8546f77

Browse files
brettz9claude
andcommitted
fix(no-unnecessary-type-assertion): don't flag array-to-tuple assertions; add preferConstToLiteralTuples
A non-`const` tuple `@type` on an array literal (`/** @type {['foo']} */ (['foo'])`, or the leading-`@type` variant) is no longer reported as redundant. The array literal only takes the tuple type *from* the assertion (without it, it widens to `string[]`), so the assertion is doing real work even though the contextually-typed expression echoes the asserted tuple straight back. Handled in both the `VariableDeclaration` and inline-cast paths. Adds a default-off `preferConstToLiteralTuples` option: when enabled, such assertions are instead reported (only when every tuple element is a literal) with an autofix that rewrites the type to the equivalent, more concise `/** @type {const} */`. Fixes #1756 Co-Authored-By: Claude Sonnet 5 <[email protected]>
1 parent c924e0a commit 8546f77

5 files changed

Lines changed: 265 additions & 2 deletions

File tree

‎.README/rules/no-unnecessary-type-assertion.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,16 @@ a member or argument of the outer cast's operand
4444
(`/** @type {DOMException} */ (reader.error).message`) is skipped entirely,
4545
since removing or unwrapping it would target the wrong expression.
4646

47+
A non-`const` tuple `@type` on an array literal
48+
(`/** @type {['foo']} */ (['foo'])`) is never reported as redundant: the array
49+
literal only takes the tuple type *from* the assertion (without it the literal
50+
widens to `string[]`), so the assertion is doing real work even though the
51+
contextually-typed expression echoes the asserted tuple straight back. This is
52+
the pre-TypeScript-4.5 stand-in for a `const` assertion. Enable the
53+
`preferConstToLiteralTuples` option to instead report such assertions when every
54+
tuple element is a literal and (under `enableFixer`) rewrite them to the
55+
equivalent, more concise `/** @type {const} */`.
56+
4757
**Note that this experimental rule requires that the `typescript` package is installed.
4858
You must also install and point to the `typescript-eslint` parser, targeting your
4959
JavaScript + JSDoc files. Note also that this rule runs fairly slowly.**
@@ -76,6 +86,7 @@ export default [
7686
// You can change these defaults
7787
checkLiteralConstAssertions: false,
7888
enableFixer: true,
89+
preferConstToLiteralTuples: false,
7990
treatAnyAsRedundant: false,
8091
typesToIgnore: [],
8192
}]
@@ -93,7 +104,7 @@ export default [
93104
|Context|`VariableDeclaration`; inline `/** @type */` casts|
94105
|Tags|`type`|
95106
|Recommended|false|
96-
|Options|`checkLiteralConstAssertions`, `enableFixer`, `treatAnyAsRedundant`, `typesToIgnore`|
107+
|Options|`checkLiteralConstAssertions`, `enableFixer`, `preferConstToLiteralTuples`, `treatAnyAsRedundant`, `typesToIgnore`|
97108

98109
## Failing examples
99110

‎docs/rules/no-unnecessary-type-assertion.md‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,16 @@ a member or argument of the outer cast's operand
4646
(`/** @type {DOMException} */ (reader.error).message`) is skipped entirely,
4747
since removing or unwrapping it would target the wrong expression.
4848

49+
A non-`const` tuple `@type` on an array literal
50+
(`/** @type {['foo']} */ (['foo'])`) is never reported as redundant: the array
51+
literal only takes the tuple type *from* the assertion (without it the literal
52+
widens to `string[]`), so the assertion is doing real work even though the
53+
contextually-typed expression echoes the asserted tuple straight back. This is
54+
the pre-TypeScript-4.5 stand-in for a `const` assertion. Enable the
55+
`preferConstToLiteralTuples` option to instead report such assertions when every
56+
tuple element is a literal and (under `enableFixer`) rewrite them to the
57+
equivalent, more concise `/** @type {const} */`.
58+
4959
**Note that this experimental rule requires that the `typescript` package is installed.
5060
You must also install and point to the `typescript-eslint` parser, targeting your
5161
JavaScript + JSDoc files. Note also that this rule runs fairly slowly.**
@@ -78,6 +88,7 @@ export default [
7888
// You can change these defaults
7989
checkLiteralConstAssertions: false,
8090
enableFixer: true,
91+
preferConstToLiteralTuples: false,
8192
treatAnyAsRedundant: false,
8293
typesToIgnore: [],
8394
}]
@@ -104,6 +115,12 @@ Whether to check `const` type assertions as redundant
104115

105116
Whether to enable the fixer that removes the redundant `@type` tag (and the JSDoc block if it becomes empty). Defaults to `true`.
106117

118+
<a name="user-content-no-unnecessary-type-assertion-options-preferconsttoliteraltuples"></a>
119+
<a name="no-unnecessary-type-assertion-options-preferconsttoliteraltuples"></a>
120+
### <code>preferConstToLiteralTuples</code>
121+
122+
Whether to report a non-`const` literal-tuple assertion on an array literal (e.g. `/** @type {['foo']} */ (['foo'])`) and fix it to the equivalent, more concise `/** @type {const} */` assertion. Defaults to `false`.
123+
107124
<a name="user-content-no-unnecessary-type-assertion-options-treatanyasredundant"></a>
108125
<a name="no-unnecessary-type-assertion-options-treatanyasredundant"></a>
109126
### <code>treatAnyAsRedundant</code>
@@ -122,7 +139,7 @@ An array list of types to ignore
122139
|Context|`VariableDeclaration`; inline `/** @type */` casts|
123140
|Tags|`type`|
124141
|Recommended|false|
125-
|Options|`checkLiteralConstAssertions`, `enableFixer`, `treatAnyAsRedundant`, `typesToIgnore`|
142+
|Options|`checkLiteralConstAssertions`, `enableFixer`, `preferConstToLiteralTuples`, `treatAnyAsRedundant`, `typesToIgnore`|
126143

127144
<a name="user-content-no-unnecessary-type-assertion-failing-examples"></a>
128145
<a name="no-unnecessary-type-assertion-failing-examples"></a>
@@ -261,6 +278,25 @@ const a = 'hello';
261278
const a = 'hello';
262279
// "jsdoc/no-unnecessary-type-assertion": ["error"|"warn", {"enableFixer":false}]
263280
// Message: The @type tag declaring "string" is redundant as TypeScript infers it automatically.
281+
282+
const arr = /** @type {['foo']} */ (['foo']);
283+
// "jsdoc/no-unnecessary-type-assertion": ["error"|"warn", {"preferConstToLiteralTuples":true}]
284+
// Message: The @type tag declaring "['foo']" is better written as the "const" assertion `/** @type {const} */` (TypeScript 4.5+).
285+
286+
/**
287+
* @type {['foo', 1]}
288+
*/
289+
const arr = ['foo', 1];
290+
// "jsdoc/no-unnecessary-type-assertion": ["error"|"warn", {"preferConstToLiteralTuples":true}]
291+
// Message: The @type tag declaring "['foo', 1]" is better written as the "const" assertion `/** @type {const} */` (TypeScript 4.5+).
292+
293+
foo(/** @type {['foo']} */ (['foo']));
294+
// "jsdoc/no-unnecessary-type-assertion": ["error"|"warn", {"preferConstToLiteralTuples":true}]
295+
// Message: The @type tag declaring "['foo']" is better written as the "const" assertion `/** @type {const} */` (TypeScript 4.5+).
296+
297+
const arr = /** @type {['foo']} */ (['foo']);
298+
// "jsdoc/no-unnecessary-type-assertion": ["error"|"warn", {"enableFixer":false,"preferConstToLiteralTuples":true}]
299+
// Message: The @type tag declaring "['foo']" is better written as the "const" assertion `/** @type {const} */` (TypeScript 4.5+).
264300
````
265301

266302

@@ -452,5 +488,15 @@ const list = /** @type {string[] | undefined} */ (
452488
);
453489

454490
const a = /* @type {number} */ (3 + 5);
491+
492+
const arr = /** @type {['foo']} */ (['foo']);
493+
494+
/**
495+
* @type {['foo']}
496+
*/
497+
const arr = ['foo'];
498+
499+
const arr = /** @type {[string]} */ (['foo']);
500+
// "jsdoc/no-unnecessary-type-assertion": ["error"|"warn", {"preferConstToLiteralTuples":true}]
455501
````
456502

‎src/rules.d.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1324,6 +1324,10 @@ export interface Rules {
13241324
* Whether to enable the fixer that removes the redundant `@type` tag (and the JSDoc block if it becomes empty). Defaults to `true`.
13251325
*/
13261326
enableFixer?: boolean;
1327+
/**
1328+
* Whether to report a non-`const` literal-tuple assertion on an array literal (e.g. `/** @type {['foo']} * / (['foo'])`) and fix it to the equivalent, more concise `/** @type {const} * /` assertion. Defaults to `false`.
1329+
*/
1330+
preferConstToLiteralTuples?: boolean;
13271331
/**
13281332
* Whether to treat `any` type casts as redundant
13291333
*/

‎src/rules/noUnnecessaryTypeAssertion.js‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ export default iterateJsdoc(({
8787
// https://typescript-eslint.io/rules/no-unnecessary-type-assertion/
8888
checkLiteralConstAssertions = false,
8989
enableFixer = true,
90+
preferConstToLiteralTuples = false,
9091
treatAnyAsRedundant = false,
9192
typesToIgnore = [],
9293
} = context.options[0] ?? {};
@@ -154,6 +155,24 @@ export default iterateJsdoc(({
154155
'The @type tag declaring "{{ type }}" is redundant as TypeScript infers it automatically for literals.' :
155156
'The @type tag declaring "{{ type }}" is redundant as TypeScript infers it automatically.';
156157

158+
const preferConstMessage =
159+
'The @type tag declaring "{{ type }}" is better written as the "const" assertion `/** @type {const} */` (TypeScript 4.5+).';
160+
161+
/**
162+
* Rewrites the reported `@type` tag's type to `const`.
163+
* @returns {void}
164+
*/
165+
const convertToConst = () => {
166+
for (const {
167+
tokens,
168+
} of /** @type {import('comment-parser').Spec} */ (types[0]).source) {
169+
if (tokens.type) {
170+
tokens.type = '{const}';
171+
break;
172+
}
173+
}
174+
};
175+
157176
/**
158177
* Whether `inferredType` is a generic reference carrying `any` type arguments
159178
* that `assertedType` replaces with concrete ones (e.g. an untyped
@@ -327,6 +346,52 @@ export default iterateJsdoc(({
327346
checker.isTypeAssignableTo(assertedBaseType, inferredBaseType);
328347
};
329348

349+
/**
350+
* A non-`const` tuple type annotation on an array literal (asserting `['foo']`
351+
* onto `['foo']`) turns the literal's inferred `T[]` into a tuple; since the
352+
* literal only takes that tuple type *from* the assertion, the assertion is
353+
* never genuinely redundant even though the contextually-typed expression
354+
* echoes the asserted tuple straight back. It is the pre-TypeScript-4.5
355+
* stand-in for a `const` assertion.
356+
* @param {any} assertedType `ts.Type`
357+
* @param {import('@typescript-eslint/utils').TSESTree.Node | null | undefined} operand
358+
* @returns {boolean}
359+
*/
360+
const isTupleConversionIdiom = (assertedType, operand) => {
361+
return assertedTypeStr !== 'const' &&
362+
operand?.type === 'ArrayExpression' &&
363+
checker.isTupleType(assertedType);
364+
};
365+
366+
/**
367+
* Whether every element of `tupleType` is a literal type, so a `const`
368+
* assertion would reproduce the same element types (`['foo', 1]` but not
369+
* `[string]`).
370+
* @param {any} tupleType `ts.Type`
371+
* @returns {boolean}
372+
*/
373+
const tupleElementsAllLiteral = (tupleType) => {
374+
const elements = checker.getTypeArguments(tupleType);
375+
return elements.length > 0 && elements.every(isLiteralType);
376+
};
377+
378+
/**
379+
* Reports an array-literal tuple assertion, offering (under `enableFixer`) a
380+
* rewrite to the equivalent, more concise `const` assertion.
381+
* @returns {void}
382+
*/
383+
const reportPreferConst = () => {
384+
utils.reportJSDoc(
385+
preferConstMessage,
386+
types[0],
387+
enableFixer ? convertToConst : null,
388+
false,
389+
{
390+
type: assertedTypeStr,
391+
},
392+
);
393+
};
394+
330395
// Positions where a bare expression of any precedence is valid and equivalent
331396
// to the parenthesized form, so a redundant `/** @type {T} */ (expr)` cast can
332397
// be unwrapped to `expr` without changing meaning.
@@ -372,6 +437,14 @@ export default iterateJsdoc(({
372437
const declInferredType = checker.getTypeAtLocation(declInitTsNode);
373438
const declAssertedType = checker.getTypeFromTypeNode(jsdocTypeNode);
374439

440+
if (isTupleConversionIdiom(declAssertedType, decl.init)) {
441+
if (preferConstToLiteralTuples && tupleElementsAllLiteral(declAssertedType)) {
442+
reportPreferConst();
443+
}
444+
445+
return;
446+
}
447+
375448
if (isRedundantAssertion(declInferredType, declAssertedType)) {
376449
utils.reportJSDoc(message, types[0], fixer, true, {
377450
type: assertedTypeStr,
@@ -441,6 +514,14 @@ export default iterateJsdoc(({
441514
checker.getTypeAtLocation(exprTsNode);
442515
const castAssertedType = checker.getTypeFromTypeNode(typeTag.typeExpression.type);
443516

517+
if (isTupleConversionIdiom(castAssertedType, node)) {
518+
if (preferConstToLiteralTuples && tupleElementsAllLiteral(castAssertedType)) {
519+
reportPreferConst();
520+
}
521+
522+
return;
523+
}
524+
444525
if (!isRedundantAssertion(castInferredType, castAssertedType)) {
445526
return;
446527
}
@@ -503,6 +584,10 @@ export default iterateJsdoc(({
503584
description: 'Whether to enable the fixer that removes the redundant `@type` tag (and the JSDoc block if it becomes empty). Defaults to `true`.',
504585
type: 'boolean',
505586
},
587+
preferConstToLiteralTuples: {
588+
description: 'Whether to report a non-`const` literal-tuple assertion on an array literal (e.g. `/** @type {[\'foo\']} */ ([\'foo\'])`) and fix it to the equivalent, more concise `/** @type {const} */` assertion. Defaults to `false`.',
589+
type: 'boolean',
590+
},
506591
treatAnyAsRedundant: {
507592
description: 'Whether to treat `any` type casts as redundant',
508593
type: 'boolean',

‎test/rules/assertions/noUnnecessaryTypeAssertion.js‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,94 @@ export default /** @type {import('../index.js').TestCases} */ ({
497497
},
498498
],
499499
},
500+
{
501+
code: `
502+
const arr = /** @type {['foo']} */ (['foo']);
503+
`,
504+
errors: [
505+
{
506+
line: 2,
507+
message: 'The @type tag declaring "[\'foo\']" is better written as the "const" assertion `/** @type {const} */` (TypeScript 4.5+).',
508+
},
509+
],
510+
filename: 'dummy.js',
511+
languageOptions,
512+
options: [
513+
{
514+
preferConstToLiteralTuples: true,
515+
},
516+
],
517+
output: `
518+
const arr = /** @type {const} */ (['foo']);
519+
`,
520+
},
521+
{
522+
code: `
523+
/**
524+
* @type {['foo', 1]}
525+
*/
526+
const arr = ['foo', 1];
527+
`,
528+
errors: [
529+
{
530+
line: 3,
531+
message: 'The @type tag declaring "[\'foo\', 1]" is better written as the "const" assertion `/** @type {const} */` (TypeScript 4.5+).',
532+
},
533+
],
534+
filename: 'dummy.js',
535+
languageOptions,
536+
options: [
537+
{
538+
preferConstToLiteralTuples: true,
539+
},
540+
],
541+
output: `
542+
/**
543+
* @type {const}
544+
*/
545+
const arr = ['foo', 1];
546+
`,
547+
},
548+
{
549+
code: `
550+
foo(/** @type {['foo']} */ (['foo']));
551+
`,
552+
errors: [
553+
{
554+
line: 2,
555+
message: 'The @type tag declaring "[\'foo\']" is better written as the "const" assertion `/** @type {const} */` (TypeScript 4.5+).',
556+
},
557+
],
558+
filename: 'dummy.js',
559+
languageOptions,
560+
options: [
561+
{
562+
preferConstToLiteralTuples: true,
563+
},
564+
],
565+
output: `
566+
foo(/** @type {const} */ (['foo']));
567+
`,
568+
},
569+
{
570+
code: `
571+
const arr = /** @type {['foo']} */ (['foo']);
572+
`,
573+
errors: [
574+
{
575+
line: 2,
576+
message: 'The @type tag declaring "[\'foo\']" is better written as the "const" assertion `/** @type {const} */` (TypeScript 4.5+).',
577+
},
578+
],
579+
filename: 'dummy.js',
580+
languageOptions,
581+
options: [
582+
{
583+
enableFixer: false,
584+
preferConstToLiteralTuples: true,
585+
},
586+
],
587+
},
500588
],
501589
valid: [
502590
{
@@ -886,6 +974,35 @@ export default /** @type {import('../index.js').TestCases} */ ({
886974
filename: 'dummy.js',
887975
languageOptions,
888976
},
977+
{
978+
code: `
979+
const arr = /** @type {['foo']} */ (['foo']);
980+
`,
981+
filename: 'dummy.js',
982+
languageOptions,
983+
},
984+
{
985+
code: `
986+
/**
987+
* @type {['foo']}
988+
*/
989+
const arr = ['foo'];
990+
`,
991+
filename: 'dummy.js',
992+
languageOptions,
993+
},
994+
{
995+
code: `
996+
const arr = /** @type {[string]} */ (['foo']);
997+
`,
998+
filename: 'dummy.js',
999+
languageOptions,
1000+
options: [
1001+
{
1002+
preferConstToLiteralTuples: true,
1003+
},
1004+
],
1005+
},
8891006
],
8901007
});
8911008

0 commit comments

Comments
 (0)