Skip to content

Parameter not matching union type not recognized when passed by reference #32270

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
mr-flannery opened this issue Jul 5, 2019 · 5 comments
Closed

Comments

@mr-flannery
Copy link

TypeScript Version: 3.3.3333, 3.4.2, 3.4.5, 3.5.2, 3.6.0-dev.20190704

Search Terms: union, union + object, union + object + bug

Code

interface A {
  a: string;
}

interface B {
  b: string;
}

const fn = (param: A | B) => param;

const obj = { a: "sdf", c: "sdf" };

fn({ a: "sd" });
fn({ b: "sd" });
fn({ a: "sd", b: "sfg" });
fn({ a: "sdf", c: "sdf" }); // this makes tsc fail
fn(obj); // this does not, but it should

Expected behavior:

tsc reports two errors, one for the last two lines respectively, as the parameters passed are essentially the same.

Actual behavior:

tsc only reports the second to last line as error, not the last one (or differently: if I comment the second to last line out, tsc does not fail, though it should)

Playground Link: https://www.typescriptlang.org/play/index.html#code/JYOwLgpgTgZghgYwgAgILIN4ChnLgLmQGcwpQBzAbiwF8stRJZEUAhTHZAI0JLJCq16CAPYgSyGCGQBeZAAoADnChwAtoXQAfZKwCUsgHzJlqtdSyjxYZCK4ArWZjyEAREQAmMVwBpkCN09vZBoLKXkMF2R3D1cQvWpwyJ5ozziaBKwkqJjfbkCYcnTM7IJUrzyA8uCMxJB5O3tMoA

Thank you very much!

@fatcerberus
Copy link

fatcerberus commented Jul 5, 2019

obj is assignable to A | B by way of structural subtyping; in particular, it satisfies A. Types are not closed: the error you do see is caused by passing in a fresh object literal with an excess property, which is checked for to catch typos and similar mistakes; it's not an actual typing violation.

I agree the error message is very misleading, see discussion starting here: #32158 (comment)

Here's a pretty good explanation (IMO) of why fn(obj) is not an error: https://basarat.gitbooks.io/typescript/docs/types/freshness.html

@MartinJohns
Copy link
Contributor

@jcalz
Copy link
Contributor

jcalz commented Jul 5, 2019

@mr-flannery
Copy link
Author

Ah, I wasn't aware of this behavior! Thank you for the quick response!

@fatcerberus
Copy link

fatcerberus commented Jul 8, 2019

@mr-flannery Yeah, under pervasive structural typing, it’s the only behavior that makes sense, because otherwise you wouldn’t be able to have subclasses at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants