Skip to content

feat(eslint-plugin): [consistent-type-assertions] add arrayLiteralTypeAssertions option #6749

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions packages/eslint-plugin/docs/rules/consistent-type-assertions.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,34 @@ const foo = <Foo props={{ ... } as Bar}/>;

<!--/tabs-->

### `arrayLiteralTypeAssertions`

Always prefer `const x: T[] = [ ... ];` to `const x = [ ... ] as T[];` (or similar with angle brackets). The rationale for this is exactly the same as for `objectLiteralTypeAssertions`.

The const assertion `const x = [1, 2, 3] as const`, introduced in TypeScript 3.4, is considered beneficial and is ignored by this option.

Assertions to `any` are also ignored by this option.

Examples of code for `{ assertionStyle: 'as', arrayLiteralTypeAssertions: 'never' }`:

<!--tabs-->

#### ❌ Incorrect

```ts
const x = [] as string[];
const y = ['a'] as string[];
```

#### ✅ Correct

```ts
const x: string[] = [];
const y: string[] = ['a'];
```

<!--/tabs-->

## When Not To Use It

If you do not want to enforce consistent type assertions.
127 changes: 92 additions & 35 deletions packages/eslint-plugin/src/rules/consistent-type-assertions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@ type MessageIds =
| 'angle-bracket'
| 'never'
| 'unexpectedObjectTypeAssertion'
| 'unexpectedArrayTypeAssertion'
| 'replaceObjectTypeAssertionWithAnnotation'
| 'replaceObjectTypeAssertionWithSatisfies';
| 'replaceObjectTypeAssertionWithSatisfies'
| 'replaceArrayTypeAssertionWithAnnotation'
| 'replaceArrayTypeAssertionWithSatisfies';
type OptUnion =
| {
assertionStyle: 'as' | 'angle-bracket';
objectLiteralTypeAssertions?: 'allow' | 'allow-as-parameter' | 'never';
arrayLiteralTypeAssertions?: 'allow' | 'never';
Copy link
Member

Choose a reason for hiding this comment

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

I didn't include an equivalent of the "allow-as-parameter" option but I can do so if there's a need.

Yeah it feels weird to have one without the other... Could you please?

}
| {
assertionStyle: 'never';
Expand All @@ -36,10 +40,15 @@ export default util.createRule<Options, MessageIds>({
'angle-bracket': "Use '<{{cast}}>' instead of 'as {{cast}}'.",
never: 'Do not use any type assertions.',
unexpectedObjectTypeAssertion: 'Always prefer const x: T = { ... }.',
unexpectedArrayTypeAssertion: 'Always prefer const x: T[] = [ ... ].',
replaceObjectTypeAssertionWithAnnotation:
'Use const x: {{cast}} = { ... } instead.',
replaceObjectTypeAssertionWithSatisfies:
'Use const x = { ... } satisfies {{cast}} instead.',
replaceArrayTypeAssertionWithAnnotation:
'Use const x: [{cast}] = [ ... ] instead.',
replaceArrayTypeAssertionWithSatisfies:
'Use const x = [ ... ] satisfies [{cast}] instead.',
},
schema: [
{
Expand All @@ -63,6 +72,9 @@ export default util.createRule<Options, MessageIds>({
objectLiteralTypeAssertions: {
enum: ['allow', 'allow-as-parameter', 'never'],
},
arrayLiteralTypeAssertions: {
enum: ['allow', 'never'],
},
},
additionalProperties: false,
required: ['assertionStyle'],
Expand All @@ -75,6 +87,7 @@ export default util.createRule<Options, MessageIds>({
{
assertionStyle: 'as',
objectLiteralTypeAssertions: 'allow',
arrayLiteralTypeAssertions: 'allow',
},
],
create(context, [options]) {
Expand Down Expand Up @@ -164,7 +177,46 @@ export default util.createRule<Options, MessageIds>({
}
}

function checkExpression(
function getReplacementSuggestions(
node: TSESTree.TSTypeAssertion | TSESTree.TSAsExpression,
annotationMessageId: MessageIds,
satisfiesMessageId: MessageIds,
): TSESLint.ReportSuggestionArray<MessageIds> {
const suggest: TSESLint.ReportSuggestionArray<MessageIds> = [];
if (
node.parent?.type === AST_NODE_TYPES.VariableDeclarator &&
!node.parent.id.typeAnnotation
) {
const { parent } = node;
suggest.push({
messageId: annotationMessageId,
data: { cast: sourceCode.getText(node.typeAnnotation) },
fix: fixer => [
fixer.insertTextAfter(
parent.id,
`: ${sourceCode.getText(node.typeAnnotation)}`,
),
fixer.replaceText(node, getTextWithParentheses(node.expression)),
],
});
}
suggest.push({
messageId: satisfiesMessageId,
data: { cast: sourceCode.getText(node.typeAnnotation) },
fix: fixer => [
fixer.replaceText(node, getTextWithParentheses(node.expression)),
fixer.insertTextAfter(
node,
` satisfies ${context
.getSourceCode()
.getText(node.typeAnnotation)}`,
),
],
});
return suggest;
}

function checkExpressionForObjectAssertion(
node: TSESTree.TSTypeAssertion | TSESTree.TSAsExpression,
): void {
if (
Expand All @@ -191,37 +243,11 @@ export default util.createRule<Options, MessageIds>({
checkType(node.typeAnnotation) &&
node.expression.type === AST_NODE_TYPES.ObjectExpression
) {
const suggest: TSESLint.ReportSuggestionArray<MessageIds> = [];
if (
node.parent?.type === AST_NODE_TYPES.VariableDeclarator &&
!node.parent.id.typeAnnotation
) {
const { parent } = node;
suggest.push({
messageId: 'replaceObjectTypeAssertionWithAnnotation',
data: { cast: sourceCode.getText(node.typeAnnotation) },
fix: fixer => [
fixer.insertTextAfter(
parent.id,
`: ${sourceCode.getText(node.typeAnnotation)}`,
),
fixer.replaceText(node, getTextWithParentheses(node.expression)),
],
});
}
suggest.push({
messageId: 'replaceObjectTypeAssertionWithSatisfies',
data: { cast: sourceCode.getText(node.typeAnnotation) },
fix: fixer => [
fixer.replaceText(node, getTextWithParentheses(node.expression)),
fixer.insertTextAfter(
node,
` satisfies ${context
.getSourceCode()
.getText(node.typeAnnotation)}`,
),
],
});
const suggest = getReplacementSuggestions(
node,
'replaceObjectTypeAssertionWithAnnotation',
'replaceObjectTypeAssertionWithSatisfies',
);

context.report({
node,
Expand All @@ -231,22 +257,53 @@ export default util.createRule<Options, MessageIds>({
}
}

function checkExpressionForArrayAssertion(
node: TSESTree.TSTypeAssertion | TSESTree.TSAsExpression,
): void {
if (
options.assertionStyle === 'never' ||
options.arrayLiteralTypeAssertions === 'allow' ||
node.expression.type !== AST_NODE_TYPES.ArrayExpression
) {
return;
}

if (
checkType(node.typeAnnotation) &&
node.expression.type === AST_NODE_TYPES.ArrayExpression
) {
const suggest = getReplacementSuggestions(
node,
'replaceArrayTypeAssertionWithAnnotation',
'replaceArrayTypeAssertionWithSatisfies',
);

context.report({
node,
messageId: 'unexpectedArrayTypeAssertion',
suggest,
});
}
}

return {
TSTypeAssertion(node): void {
if (options.assertionStyle !== 'angle-bracket') {
reportIncorrectAssertionType(node);
return;
}

checkExpression(node);
checkExpressionForObjectAssertion(node);
checkExpressionForArrayAssertion(node);
},
TSAsExpression(node): void {
if (options.assertionStyle !== 'as') {
reportIncorrectAssertionType(node);
return;
}

checkExpression(node);
checkExpressionForObjectAssertion(node);
checkExpressionForArrayAssertion(node);
},
};
},
Expand Down
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy