-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Detect unreachable code in more scenarios #39995
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
believe this is by design although I can't comment on what the intent is, see https://www.staging-typescript.org/tsconfig#allowUnreachableCode
|
I would say that these unreachable branches of logical operators fall under the category of, quote from the docs
|
Some use cases that aren't just code no one would reasonably write (e.g. |
@RyanCavanaugh I agree that some of these may not be too useful, but others where TypeScript knows that the value is truthy (objects, mostly) I think are helpful.
|
Related: the nullish operator offers other further occasion to detect errors, as I mention in #43040 |
It still happens, I just had this scenario:
besides not resulting in an unreachable code error, it also has a wrong return type |
I think this feature is especially useful when working with some frameworks. In some ImGUI frameworks, an event listener is like this: // _.button: (text: string) => boolean
if(_.button("Click me")){
button is clicked, now do something;
}
// _.span: (text: string) => false
if(_.span("Hello")){
mistake; // this line should be marked as unreachable, to indicate this is a mistake.
} |
What framework has methods that are hardcoded to return |
I completely agree with you. However, I want to ensure that the return type of components is consistent – and perhaps the cost of detecting the literal falsy condition of an if-statement is very low? |
related issue: #45267 |
Search Terms
logical assignment binary expression dead never truthy falsy
Suggestion
Raise compiler errors when the left side of an expression using a logical operator (
&&
or||
) is unrechable.Also detect unreachable branches of ternary expressions.
Use Cases
Code that is statically verifiable to be unreahable is almost always a programmer error so TypeScript should detect unreachable code in more scenarios.
Examples
Playground link.
It would also be nice to expand unreachable code checks to other expressions that are known to be truthy or falsy eg. object/array literals, NaN eg.
Playground link.
Finally, detecting unreachable branches of a ternary expression
Playground link
Checklist
My suggestion meets these guidelines:
There would be new type errors. The extra safety could be opted into by extending the
allowUnreachableCode
flag or creating a new flag.The text was updated successfully, but these errors were encountered: