-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Description
Search Terms
type guard always-false warning
Suggestion
When a typeguard is always false, the guarded variable is type never within the body. While you can't actually look up any properties on never, you can pass it anywhere or assign it to anything and there's absolutely no warnings. Calling a typeguard function with an argument that has no overlap with the guard should produce a warning.
Use Cases
My immediate motivation is #24436 (comment), where if Number.isFinite could be written as a typeguard (this would also need a narrower number subtype, see e.g. #32188) then it could easily be allowed to be called with a number|string, but no additional gymnastics would be required to warn if calling with a guaranteed non-number.
In general there's not a good reason to call an always-false typeguard. This is quite different from the always-true case where defensive coding comes into play.
Examples
declare const x: string;
if (isNumber(x)) { // Should warn: "condition is always false"
usePrivate(x);
}If usePrivate requires a private type that this scope doesn't have access to construct, then it would be nice if this code warned somewhere. Instead, it currently just narrows x to never and allows doing whatever you want with it.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- I don't have a good sense of how much this would break, but I expect any breakages would be exposing legitimate errors.
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.