Skip to content

Commit

Permalink
fix(eslint-plugin): [no-inferrable] fix optional param to valid code (#…
Browse files Browse the repository at this point in the history
…5342)

* fix(eslint-plugin): [no-inferrable] fix optional param to valid code

* Add definite assignment
  • Loading branch information
Josh-Cena committed Jul 18, 2022
1 parent 9ed8fe3 commit 98f6d5e
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
13 changes: 12 additions & 1 deletion packages/eslint-plugin/src/rules/no-inferrable-types.ts
Expand Up @@ -46,6 +46,8 @@ export default util.createRule<Options, MessageIds>({
},
],
create(context, [{ ignoreParameters, ignoreProperties }]) {
const sourceCode = context.getSourceCode();

function isFunctionCall(
init: TSESTree.Expression,
callName: string,
Expand Down Expand Up @@ -215,7 +217,16 @@ export default util.createRule<Options, MessageIds>({
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);
},
});
}

Expand Down
49 changes: 48 additions & 1 deletion packages/eslint-plugin/tests/rules/no-inferrable-types.test.ts
Expand Up @@ -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') => {};",
Expand Down

0 comments on commit 98f6d5e

Please sign in to comment.