-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Allow type guards to be type checked #47468
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Duplicate of #29980.
TypeScript does not follow SemVer. |
Right, sorry I didn't find it first. Yet I think this one has several differences:
|
Different competing syntaxes don't warrant new issues. A different syntax proposal can be commented on existing issues. The TypeScript team mentioned this several times (not bothering to look it up now). Checking for nulls is common, and trivially solved with a simple function. And for type guards you should just write more unit tests. The TypeScript team disagrees (in the other issue). The very point of used-defined type guards is to support the compiler with type checks that the compiler itself can't verify. This is true for the majority of cases, except for a few very simply type guards. And I personally would doubt that this narrow use-case would justify the additional complexity in the compiler. |
If type predicates could be automatically verified, we wouldn’t need them. TypeScript already does control flow-based narrowing, so nine times out of ten you’re only writing a type predicate because there’s a type check the compiler couldn’t help you with. It isn’t like encryption where finding the key is harder than verifying it; verifying through control flow that a type has been narrowed properly is exactly the same problem as doing the narrowing directly. |
Suggestion
Allow type guards to be type checked
🔍 Search Terms
Type guards narrowing
✅ Viability Checklist
My suggestion meets these guidelines:
⭐ Suggestion
Type guards are sometimes used when TS has no knowledge what's happening here and we need some kind of
believeMe
to enforce some invariants we can guarantee as developers. But there are plenty of trivial cases that can be inferred by compiler itself. And I strongly believe that if it can do it it should since it helps us with human mistakes.It can be implemented in both breaking and non-breaking manner. I do believe that breaking manner would make future more safe but since I know how people love backward compatibility even between major versions I think an
infer
keyword may be used to fix the gap. It could look like📃 Motivating Example
There are multiple questions with hundreds of upvotes on SO that asks for different narrowings and they all repeat a similar pattern like
The problem is compiler doesn't check it at all and we can always rewrite it as:
or
💻 Use Cases
const notNulls: string[] = ['foo', 'bar', null, 'zoo', null].filter(notEmpty)
The text was updated successfully, but these errors were encountered: