Skip to content

Compound assignments and narrowing #9815

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
zhuravlikjb opened this issue Jul 19, 2016 · 4 comments
Closed

Compound assignments and narrowing #9815

zhuravlikjb opened this issue Jul 19, 2016 · 4 comments
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript

Comments

@zhuravlikjb
Copy link

Noticed a very strange behaviour with compound assignments and narrowing.

This works fine with a normal assignment:

function moooo12() {
    var x: string | number = 5;
    x = x + "a";  // RHS "x" is narrowed, LHS "x" is not, everything right
    x;
}

This doesn't work, though:

function moooo12() {
    var x: string | number = 5;
    x += "a"; // the compiler thinks that "x" is "number" here, and states that "string" is not assignable to it
    x;
}

Seems that in the last case the compiler shouldn't narrow the LHS "x" anyways, but rather it should specially calculate the result type of "+=" assignment taking into account the narrowed version of "x".

@DanielRosenwasser
Copy link
Member

@ahejlsberg and I have actually discussed this: #9013 (comment)

Is there a use case you had in mind @zhuravlikjb?

@zhuravlikjb
Copy link
Author

@DanielRosenwasser No particular use cases. I was supporting some corner cases in my own type guards mechanism, and stumbled upon the fact that the TypeScript compiler behaves strangely with compound assignments. I'm always a source of theoretical questions, sorry. :)

@DanielRosenwasser
Copy link
Member

No worries! Looks like we have that in common. 😄

@DanielRosenwasser DanielRosenwasser added the Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature label Jul 19, 2016
@mhegazy mhegazy added the Suggestion An idea for TypeScript label Sep 20, 2016
@RyanCavanaugh
Copy link
Member

Closing due to lack of additional interest. The behavior here seems at least sometimes desirable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

4 participants