Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Enhancement: [restrict-template-expressions] allow expressions with never type #5325

Closed
@mikeyhew

Description

@mikeyhew

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/restrict-template-expressions#allownullish

Description

The restrict-template-expressions rule currently complains if the template expression has type never. This occurs, for example, if you have code like this:

// more variants may be added to Foo in the future
type Foo =
  | {type: "a", value: number};

function checkFoosAreMatching(foo1: Foo, foo2: Foo) {
  if (foo1.type !== foo2.type) {
    // since Foo currently only has one variant, this code is never run,
    // and `foo1.type` has type `never`.
    throw new Error(`expected ${foo1.type}, found ${foo2.type}`);
                                                  // ^ Invalid type "never" of template literal expression.
  }
}

I don't see the benefit of the lint warning here, which complains that foo1.type and foo2.type have type never and says, Invalid type "never" of template literal expression.

I am suggesting changing the lint rule's behaviour to allow template expressions to have the type never. This could be done as a new option called allowNever, although I personally don't see the point in giving the option to disallow never in template expressions. Why should this lint rule be complaining about dead code?

Fail

const foo: "a" | null;
const bar: "a";

if (foo !== bar) {
    // `foo` has type `null`, which is not allowed
    // with the default options for this rule
    throw new Error(`${foo} and ${bar} are not equal);
}

Pass

const foo: "a";
const bar: "a";

if (foo !== bar) {
    // `foo` and `bar` have type `never`, which should be allowed
    // by this rule
    throw new Error(`${foo} and ${bar} are not equal);
}

Additional Info

This same logic should also apply to similar rules like restrict-plus-operands (no need to complain that an operand has type never), although I haven't checked to see how that rule behaves for never operands.

Metadata

Metadata

Assignees

No one assigned

    Labels

    accepting prsGo ahead, send a pull request that resolves this issueenhancement: 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