diff --git a/packages/eslint-plugin/src/rules/no-inferrable-types.ts b/packages/eslint-plugin/src/rules/no-inferrable-types.ts index 9adb4bca9ec..e77b694cc70 100644 --- a/packages/eslint-plugin/src/rules/no-inferrable-types.ts +++ b/packages/eslint-plugin/src/rules/no-inferrable-types.ts @@ -46,6 +46,8 @@ export default util.createRule({ }, ], create(context, [{ ignoreParameters, ignoreProperties }]) { + const sourceCode = context.getSourceCode(); + function isFunctionCall( init: TSESTree.Expression, callName: string, @@ -215,7 +217,16 @@ export default util.createRule({ data: { type, }, - fix: fixer => fixer.remove(typeNode), + *fix(fixer) { + if ( + (node.type === AST_NODE_TYPES.AssignmentPattern && + node.left.optional) || + (node.type === AST_NODE_TYPES.PropertyDefinition && node.definite) + ) { + yield fixer.remove(sourceCode.getTokenBefore(typeNode)!); + } + yield fixer.remove(typeNode); + }, }); } diff --git a/packages/eslint-plugin/tests/rules/no-inferrable-types.test.ts b/packages/eslint-plugin/tests/rules/no-inferrable-types.test.ts index d85806b69c4..cfea578b9f6 100644 --- a/packages/eslint-plugin/tests/rules/no-inferrable-types.test.ts +++ b/packages/eslint-plugin/tests/rules/no-inferrable-types.test.ts @@ -156,7 +156,54 @@ class Foo { invalid: [ ...invalidTestCases, - + { + // This is invalid TS semantic, but it's trivial to make valid anyway + code: 'const fn = (a?: number = 5) => {};', + output: 'const fn = (a = 5) => {};', + options: [ + { + ignoreParameters: false, + }, + ], + errors: [ + { + messageId: 'noInferrableType', + data: { + type: 'number', + }, + line: 1, + column: 13, + }, + ], + }, + { + // This is invalid TS semantic, but it's trivial to make valid anyway + code: ` +class A { + a!: number = 1; +} + `, + output: ` +class A { + a = 1; +} + `, + options: [ + { + ignoreProperties: false, + }, + ], + errors: [ + { + messageId: 'noInferrableType', + data: { + type: 'number', + }, + line: 3, + column: 3, + }, + ], + }, { code: "const fn = (a: number = 5, b: boolean = true, c: string = 'foo') => {};", output: "const fn = (a = 5, b = true, c = 'foo') => {};",