microsoft / microsoft/TypeScript

Control flow analysis should "work" in unreachable code

Open
#26,914 11 comments 29 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Control Flow
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: master

Search Terms: unreachable throw return narrowing

Code

function fn() {
    // TODO: Finish writing this function!
    return;

    const h = Math.random() > 0.5 ? 'h' : undefined;

    if (h) {
        // Error, wat
        const a: string = h;
    }
}

Expected behavior: No error

Actual behavior: Error - h is possibly undefined

We get "bug" reports like this every once in a while, and it's hard to understand why the narrowing just stops working because the code isn't reachable. This also makes it difficult to insert debugging throws/returns earlier in the function.

e.g. https://twitter.com/aendrew/status/1037301561062514688

Playground Link: http://www.typescriptlang.org/play/#src=function%20fn()%20%7B%0A%20%20%20%20%2F%2F%20Not%20done%20yet%0A%20%20%20%20return%3B%0A%0A%20%20%20%20const%20h%20%3D%20Math.random()%20%3E%200.5%20%3F%20'h'%20%3A%20undefined%3B%0A%20%20%20%20const%20d%20%3D%20(arg%3A%20string)%20%3D%3E%20arg%3B%0A%0A%20%20%20%20if%20(h)%20%7B%0A%20%20%20%20%20%20%20%20const%20a%20%3D%20d(h)%3B%0A%20%20%20%20%7D%0A%7D%0A

Related Issues: Believe there's one out there somewhere

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the supplied TypeScript Playground reproduction and confirm that the narrowing error occurs after an unreachable return. Trace the compiler's control-flow analysis for unreachable statements, then add or update a regression test so the narrowed value is accepted and the existing reachable-code behavior remains unchanged.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.