-
Notifications
You must be signed in to change notification settings - Fork 12.7k
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
Can't access potential member on union type #18750
Comments
That would make the type system unsound. Doing so would cause all sorts of bad code. You need to understand better how the typing system works. When you have a Schrödinger's cat type like that, TypeScript will only allow you to access the properties it knows are in common. If you wanted it to work, you could change the type: interface Foo {
foo: string;
}
interface Bar {
bar: string;
}
function test(item: Foo & Bar) {
console.log(item.foo || item.bar)
} But it depends on what you are trying to do and represent properly, because you could narrow the type as well: interface Foo {
foo: string;
}
interface Bar {
bar: string;
}
function isFoo(value: any): value is Foo {
return 'foo' in value;
}
function test(item: Foo | Bar) {
console.log(isFoo(item) ? item.foo : item.bar)
} |
This has been the behavior forever and is not a bug. See #805 |
But what about stating that type of |
No. If you want interface Bar {
bar: string;
foo?: string;
} The typing system is designed to be sound. It isn't designed to be abused. |
TypeScript Version: 2.4.0 / nightly (2.5.0-dev.201xxxxx)
Code
Expected behavior:
This pattern is very common in javascript, that would be great to make it valid in typescript.
Actual behavior:
The text was updated successfully, but these errors were encountered: