Skip to content
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

Premature literal type widening? #17363

Closed
ethanresnick opened this issue Jul 23, 2017 · 2 comments
Closed

Premature literal type widening? #17363

ethanresnick opened this issue Jul 23, 2017 · 2 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@ethanresnick
Copy link
Contributor

TypeScript Version: 2.4.1

Code

type AorBValuedObj = { 'test': 'a' | 'b' };

const makeTestObj = () => {
    const x = (<boolean>true) ? 'a' : 'b';
    return { 'test': x };
};

const x2: AorBValuedObj = makeTestObj();

Expected behavior:
Assignment to x2 succeeds.

Actual behavior:
Assignment fails because the result type of makeTestObj is {'test': string} rather than {'test': 'a' | 'b' }.

I vaguely recall that the rules for widening depend on whether a value is mutable, so my guess is that the widening is happening on the property's type because properties are mutable. Still, would it make sense not to widen here? Or maybe the current behavior is good, since it forces me declare explicitly that makeTestObj returns an AorBValuedObj?

@ahejlsberg
Copy link
Member

This is working as intended. In makeTestObj you need some indication that you don't want the test property widened (e.g. a return type annotation or a type assertion on the returned value). Absent that, the compiler widens the type because a property is a mutable location.

@ahejlsberg ahejlsberg added the Working as Intended The behavior described is the intended behavior; this is not a bug label Jul 24, 2017
@mhegazy
Copy link
Contributor

mhegazy commented Aug 17, 2017

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

3 participants