Let's say I have dynamic object which has a union type:
foo: {[key in 'num' | 'str' | 'obj']: number | string | object};
Now i assign object properties as follow:
foo.num = 1;
foo.str = 'text';
foo.obj = {};
And it works. However when I try to access:
foo.num
And use this value f.e. to reduce it by summing up all foo.num properties - I can't because compiler tells me that foo.num is type of union. How to tell compiler that foo.num is type of number? I know there is a way with as but it is not elegant way. I've been looking for answer in SO, Medium and other programming sites but couldn't find solution.
Edit:
It was just an example. My real case is like this. I have an array of objects which I have to group by one of their property which is Enum type and then map them. So I am doing something like this:
Object.values(Enum).forEach(
enum => subjects[enum].next(
array
.filter(object => object.type === enum)
.map(object => object.payload)
)
);
I though best way would be create object which will store all of subjects but this make all subjects inside of this object of union type. If enum values change for some reason, I will need to change only enum type, nothing more.