Description
Before You File a Proposal Please Confirm You Have Done The Following...
- I have searched for related issues and found none that match my proposal.
- I have searched the current rule list and found no rules that match my proposal.
- I have read the FAQ and my problem is not listed.
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.