-
Notifications
You must be signed in to change notification settings - Fork 12.3k
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
Empty object or type ({} | Type
) doesn't work as expected
#8032
Comments
You can't assign the What was your intent in writing |
You are most likely correct. I'm trying to have a property where it could be a predefined type or an empty object
|
In that case, what you wrote is correct (usually people use For this example, the best solution would be a type assertion, since the compiler doesn't know whether or not the interface IAnimal {
legs: Number;
}
interface IHouse {
cat: {} | IAnimal;
}
const obj: IHouse = {
cat: {
legs: 2,
},
};
(obj.cat as IAnimal).legs = 5; // OK
obj.cat = {}; There are other solutions you could play with (writing a type predicate, making As an aside, you definitely want to use |
Interesting, thanks for clearing that up. I believe I see how it works now. Because there's no clear way to discern between I got it work with making Thanks for the |
Basically. The rule for union types is that we only allow an operation if it would be legal to do on each member of the union. Since Depending on context we can sometimes tell which you happen to have and will "narrow" to one member of the union (e.g. if there's an |
@RyanCavanaugh what if I actually want to define an empty object that may not have any properties? (such that the only acceptable value for that object is |
use |
|
TypeScript Version:
1.8.9
Code
Expected behavior:
Should be able to assign
cat.legs
or{}
interchangeably.Actual behavior:
Unable to assign
legs
of{} | IAnimal
.The text was updated successfully, but these errors were encountered: