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

Bug with type discrimination and string literal types. #13628

Closed
johnfn opened this issue Jan 23, 2017 · 4 comments
Closed

Bug with type discrimination and string literal types. #13628

johnfn opened this issue Jan 23, 2017 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@johnfn
Copy link

johnfn commented Jan 23, 2017

The following code gives an error on the assignment to x:

type Bar = "A" | "B"
type Foo = { key: "a", name: string } | { key: "b", name: Bar }

const x: Foo = { key: "b", name: "A" }

There are multiple weird things that get rid of the error, including:

  1. Changing { key: "a", name: string } to { key: "a" }.
  2. Changing name: "A" to name: "A" as Bar
@alitaheri
Copy link

This issue have been around for a while, it boils down to this:

const obj = {b: 'A'};
type A = 'A';
const a: A = obj.b; // ---> [ts] Type 'string' is not assignable to type '"A"'.

Not much can be done here. typing b as 'A' has too many consequences and breaks way too many code. This issue can't be solved until Expando Objects come to rescue. With those around b can just be typed 'A' and expand to include more literals or morph into string. no code will break and this issue will be solved for good ❤️

@johnfn
Copy link
Author

johnfn commented Jan 23, 2017

I understand why your code doesn't work, but I still don't see why mine doesn't, as I have explicitly given the type of x to be Foo.

If I wrote const obj: { b: A } = { b: 'A' } in your code, I would expect it to work as well.

@alitaheri
Copy link

Right, sorry, I didn't initially understand the issue you reported. I think what you expect the compiler to do is valid. This is a bug indeed 👍

@mhegazy
Copy link
Contributor

mhegazy commented Jan 23, 2017

Duplicate of #13580

@mhegazy mhegazy added the Duplicate An existing issue was already created label Jan 23, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants