Skip to content

Enhancement: [no-unnecessary-condition] additionally check typeof expression when it possible #11404

@zanminkian

Description

@zanminkian

Before You File a Proposal Please Confirm You Have Done The Following...

My proposal is suitable for this project

  • I believe my proposal would be useful to the broader TypeScript community (meaning it is not a niche proposal).

Link to the rule's documentation

https://typescript-eslint.io/rules/no-unnecessary-condition/

Description

Let's say:

function foo(): string | undefined {
  // bla bla bla
}
const bar = foo();
if (typeof bar === 'string') { // It's ok
  // bla bla bla
}

One day, I refactored the foo function to return string only:

function foo(): string {
  // bla bla bla
}
const bar = foo();
if (typeof bar === 'string') { // Smelly code. bar is always string. But no-unnecessary-condition does not report it
  // bla bla bla
}

Fail

const str:string = 'foo';
if (typeof str === 'string') {
  // bla bla bla
}

Pass

const str:string|undefined = 'foo';
if (typeof str === 'string') {
  // bla bla bla
}

Additional Info

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    duplicateThis issue or pull request already existsenhancement: plugin rule optionNew rule option for an existing eslint-plugin rulepackage: eslint-pluginIssues related to @typescript-eslint/eslint-plugin

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions