Skip to content

Union types get narrowed unexpectedly #38423

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

Closed
mmktomato opened this issue May 8, 2020 · 2 comments
Closed

Union types get narrowed unexpectedly #38423

mmktomato opened this issue May 8, 2020 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@mmktomato
Copy link

TypeScript Version:
3.8.3 and Nightly

Search Terms:

  • type inference
  • union type
  • narrowing
  • callback
  • function

Code

const fn1 = (cb: (n: number) => void) => {
    cb(0);
};

const fn2 = () => {
    let a: number | string = "";
    fn1(n => a = n);
    return a;
};

type T = ReturnType<typeof fn2>;  // T is string

Expected behavior:
I define a as number | string explicitly. So I expect T is number | string.

Actual behavior:
T is string.

Playground Link:
https://www.typescriptlang.org/play/?ts=nightly#code/MYewdgzgLgBAZmAjDAvDAFMARgLg2PMAVwFssBTAJwEpUA+GANxAEsATWlBgbwCgYBMbOgAM1ANy8AvpN6hIsBACZUGTj36CANuVgBDQqQqUYAHxjRKLMAHNVAInuTB8JOjD0Ye1WAmaBlLpElB56kjK8vFAAngAO5DAAKqoASkEhiXHkADwx8SBwrkp04gIA9GVJMCwQFlBWtkA

Related Issues:
#9998

@nmain
Copy link

nmain commented May 8, 2020

Two things going on here.

a is initially typed to string:
Duplicate of #8513
My search terms were union narrowing assignment
Also see discussion in #31734

fn1(...) does not reset the narrowing on a, or renarrow a to number:
Duplicate of #9998

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label May 8, 2020
@mmktomato
Copy link
Author

Thank you. I understand the situation and the background.
Fortunately my case is enough to do like:

const fn2 = (): number | string => {
    // ...
};

type T = ReturnType<typeof fn2>;  // T is number | string

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants