Skip to content

Enhancement: [no-unnecessary-condition] report on type guards usages where the type is already equal #10007

Closed
@kirkwaiblinger

Description

@kirkwaiblinger

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

Report when checking type guards, where the type of the variable is already exactly equal to the type guard return type.

Fail

function isBool(x: unknown): x is boolean {
    return typeof x === 'boolean';
}

declare const b: boolean;

if (isBool(b)) { // this is unnecessary, since b is already boolean.
}

Pass

declare const maybeBoolean: boolean | string;

if (isBool(maybeBoolean)) { // necessary - might not a boolean.
}

declare const t: true;

if (isBool(t)) { // debatable - t is a subtype of boolean, not exactly equal. this has some funny effects in the type system.
    console.log(t); // t gets widened to boolean here, even though it was typed as true.
} else {
    console.error(t); // t also widened to boolean here.
}

Additional Info

#9076 is in a similar domain, checking unnecessary assertion functions.

Metadata

Metadata

Labels

enhancement: plugin rule optionNew rule option for an existing eslint-plugin rulelocked due to agePlease open a new issue if you'd like to say more. See https://typescript-eslint.io/contributing.package: eslint-pluginIssues related to @typescript-eslint/eslint-pluginteam assignedA member of the typescript-eslint team should work on this.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions