Skip to content

never return type not handled when function has implicit type #60609

Closed as not planned
@jorrit

Description

@jorrit

🔎 Search Terms

When a function has return type never it can be used as a kind of falsy check:

const test = (input: A|undefined): void => {
  if (input === undefined) {
    neverReturn();
  }

  // input is never undefined here.
  console.log(input.id);
}

This does not work in all cases, as demonstrated on the playground link. Only when the const has an explicit type never is handled correctly.

🕗 Version & Regression Information

It does not work in the any TypeScript version available at the PlayGround.

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=3.8.3#code/JYOwLgpgTgZghgYwgAgILIN4ChnOAEwC5kQBXAWwCNoBuLAXyywQHsQBnMEiAN2gCUIYUlBABGZAF5kACgCUxEL2hSAfJhzIwACygsA7t0MBRKHqgyA5Kkty69OszactEThOkzQAB1JhiqAA+pCD4EDCgEPgKyDwsBGoauMAwsj5+UpLSIWERStFJuNx8UILComLydLiMmgD0dcgAkiC+XAhwIMicwAA2vcjUyDnhkfjIiKxQ+KAA5losyAAqAMoAdJqsHCy9EGu9LLNerX5rBHYMTFsuSiVlIiAATMTyibcqnjHvUInYuDp6QxKExmFgWay2eyOa5cSCcR5SNInfxoYKhUb5GJxBKSdR-PCpY5tTLZdF5KJyQq4b73USPKqaWq4BrNZF4djIMKQKDkMYLQYoEAsLgjcn4Da4a47PYHI7pMBnaL2LBAA

💻 Code

interface A {
  id: number;
}

const neverReturn1 = (): never => {
  throw new Error('A');
};

const test1 = (input: A|undefined): void => {
  if (input === undefined) {
    neverReturn1();
  }

  // Input can still be undefined according to TS.
  console.log(input.id);
}

const neverReturn2: () => never = (): never => {
  throw new Error('A');
};

const test2 = (input: A|undefined): void => {
  if (input === undefined) {
    neverReturn2();
  }

  // Input is determined to be not undefined.
  console.log(input.id);
}

🙁 Actual behavior

Error: Object is possibly 'undefined'. in test1.

🙂 Expected behavior

No errors, because neverReturn1() never returns.

Additional information about the issue

No response

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