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

Union types behaviour bug? #10311

Closed
bartosz-k opened this issue Aug 13, 2016 · 4 comments
Closed

Union types behaviour bug? #10311

bartosz-k opened this issue Aug 13, 2016 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@bartosz-k
Copy link

TypeScript Version: 2.1.0-dev.20160723

Code

// A *self-contained* demonstration of the problem follows...
export type WebSocketMessage = {type: 'userInfo'} | {type: 'chat'};
export let WSSend = (ws: WebSocket, message: WebSocketMessage) => {
};

let ws = new WebSocket('');
let message = {type: 'chat'};
WSSend(ws, message);

Expected behavior:
No error. Noticed though that it passes:

export type WebSocketMessage = {type: 'userInfo'} | {type: 'chat'};
export let WSSend = (ws: WebSocket, message: WebSocketMessage) => {
};

let ws = new WebSocket('');
//let message = {type: 'chat'};
WSSend(ws, {type: 'chat'});

Actual behavior:

Error:(13, 12) TS2345:Argument of type '{ type: string; }' is not assignable to parameter of type '{ type: "userInfo"; } | { type: "chat"; }'.
  Type '{ type: string; }' is not assignable to type '{ type: "chat"; }'.
    Types of property 'type' are incompatible.
      Type 'string' is not assignable to type '"chat"'.
@normalser
Copy link

It's because let message = {type: 'chat'} will by default infer as {type: string} which is not assignable to {type: 'userInfo'} | {type: 'chat'} which is using string literals.

There is a discussion about possible syntax for literals #10195

@bartosz-k
Copy link
Author

yeah, but IMO it should work as users would expect, which is no error without additional syntax. If it's not planned to be implemented at all, let's close the issue.

@DanielRosenwasser
Copy link
Member

Duplicate of #9489.

@DanielRosenwasser DanielRosenwasser added the Duplicate An existing issue was already created label Aug 13, 2016
@DanielRosenwasser
Copy link
Member

@Bartq A workaround exists to just add a type annotation to your variable,

let message: WebSocketMessage = {type: 'chat'};
WSSend(ws, message);

or to pass the object literal in directly.

@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

3 participants