Skip to content

Guaranteed unreachable code should not be used to infer type #45746

Closed
@anddoutoi

Description

@anddoutoi

Bug Report

TS should not infer type from code that is guaranteed to be unreachable. This is mainly a DX issue that gives the developer false information from return types that has been temporarily changed during spiking or when a developer just want to test something out.

Scenario is that a function returns a type and you want to find out if what happens if you would change that return type. So you add a new return statement above the old one, exiting the function earlier without touching the old code.

Workarounds is the obvious:

  • remove the code
  • comment out the code

In most cases it's more efficient to just do an early return. This however gives us false information.

🔎 Search Terms

  • Developer experience
  • Unreachable code
  • Union types

🕗 Version & Regression Information

v4.4.2, also tested in v4.3.5.

⏯ Playground Link

Playground link with relevant code

💻 Code

interface Foo {
    foo: string;
}

interface Bar {
    bar: string;
}

function getFoo(): Foo {
    return {
        foo: "foo"
    };
}

function getBar(): Bar {
    return {
        bar: "bar"
    };
}

// return type of fubar should be Foo, not Foo | Bar. TS should not infer trully unreachable code
function fubar() {
  const foo: Foo = getFoo();
  const bar: Bar = getBar();

  return foo;

  return bar;
}

function logFoo(foo: Foo) {
    console.log(foo.foo);
}

function main() {
    const myFubar = fubar();

    // myFubar is Foo | Bar now, something it can never be in this case!
    
    logFoo(myFubar);
}

🙁 Actual behavior

Return type of fubar() is the union of Foo | Bar.

🙂 Expected behavior

Return type of fubar() should be Foo, not Foo | Bar. TS should not infer types from code that is guaranteed to be unreachable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions