Skip to content

Loss of type inference after assignment #42821

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
zkrising opened this issue Feb 16, 2021 · 2 comments
Closed

Loss of type inference after assignment #42821

zkrising opened this issue Feb 16, 2021 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@zkrising
Copy link

zkrising commented Feb 16, 2021

Bug Report

πŸ”Ž Search Terms

Loss of type information, Forgotten type inference.

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about common bugs that aren't bugs.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

let x: unknown = "foo";

if (typeof x === "string") {
    // typescript now knows that this is a string from inference.
    let y: string = x;

    // perform any assignment to x;
    // I found this by calling x = x.substring(1), but it appears just reassigning x works.
    x = x;

    // similarly; x = "bar" still results in x being unknown. Any assignment to x results in the type inference being forgotten.

    // x is now unknown?
    // Type 'unknown' is not assignable to type 'string'.(2322)
    y = x;
}

πŸ™ Actual behavior

Typescript correctly infers that x is a string if typeof x === "string", however, it seems to forget this if x is assigned to, including trivial assignments.

πŸ™‚ Expected behavior

x is inferred to be a string, so x = x should be a no-op -> x should still be a string. This issue in and of itself is not too important, but any assigment to x (including ones that guaranteeably return a string, like x = x.substring(1) also causes TS to forget its type inference.)

I apologise if this is known or not a bug, I could not find anything similar reported on the issue tracker.

@zkrising
Copy link
Author

More information: This seems to only happen with x: unknown. This does not happen with other cases of type inference, such as when x: string | number, or even x: any. This is presumably a bug with unknown.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Feb 16, 2021
@RyanCavanaugh
Copy link
Member

See #27706

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

2 participants