Skip to content

Commit

Permalink
feat(eslint-plugin): [consistent-type-assertions] add suggestions for…
Browse files Browse the repository at this point in the history
… objectLiteralTypeAssertions (#6642)

* Add suggestions for objectLiteralTypeAssertions

* Add additional test cases

* Capture parentheses

* Use changes from other PR

---------

Co-authored-by: Josh Goldberg <git@joshuakgoldberg.com>
  • Loading branch information
NotWoods and JoshuaKGoldberg committed Mar 21, 2023
1 parent dd5167f commit 720e811
Show file tree
Hide file tree
Showing 2 changed files with 285 additions and 1 deletion.
42 changes: 41 additions & 1 deletion packages/eslint-plugin/src/rules/consistent-type-assertions.ts
Expand Up @@ -8,7 +8,9 @@ type MessageIds =
| 'as'
| 'angle-bracket'
| 'never'
| 'unexpectedObjectTypeAssertion';
| 'unexpectedObjectTypeAssertion'
| 'replaceObjectTypeAssertionWithAnnotation'
| 'replaceObjectTypeAssertionWithSatisfies';
type OptUnion =
| {
assertionStyle: 'as' | 'angle-bracket';
Expand All @@ -24,6 +26,7 @@ export default util.createRule<Options, MessageIds>({
meta: {
type: 'suggestion',
fixable: 'code',
hasSuggestions: true,
docs: {
description: 'Enforce consistent usage of type assertions',
recommended: 'strict',
Expand All @@ -33,6 +36,10 @@ 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 = { ... }.',
replaceObjectTypeAssertionWithAnnotation:
'Use const x: {{cast}} = { ... } instead.',
replaceObjectTypeAssertionWithSatisfies:
'Use const x = { ... } satisfies {{cast}} instead.',
},
schema: [
{
Expand Down Expand Up @@ -184,9 +191,42 @@ 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)}`,
),
],
});

context.report({
node,
messageId: 'unexpectedObjectTypeAssertion',
suggest,
});
}
}
Expand Down

0 comments on commit 720e811

Please sign in to comment.