Skip to content

feat(eslint-plugin): [consistent-type-assertions] add suggestions for objectLiteralTypeAssertions #6642

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

Merged
Merged
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
42 changes: 41 additions & 1 deletion packages/eslint-plugin/src/rules/consistent-type-assertions.ts
Original file line number Diff line number Diff line change
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
Loading