Suppose I have a dynamic object with a union type:
data: {[key in 'num' | 'str' | 'obj']: number | string | object};
I set the object properties as follows:
data.num = 1;
data.str = 'text';
data.obj = {};
Everything seems to be working fine. However, when I try to access:
data.num
and use this value to perform operations like summing up all data.num
properties, I face an issue because the compiler indicates that data.num
is of a union type. How can I explicitly specify to the compiler that data.num
is of type number
? I am aware of using as
, but I find it to be less elegant. I have searched for solutions on platforms like Stack Overflow, Medium, and other programming sites without success.
Edit:
This was just an example. In reality, I have an array of objects that need to be grouped based on one of their Enum properties and then mapped. Here's how I'm approaching it:
Object.values(Enum).forEach(
enum => subjects[enum].next(
array
.filter(object => object.type === enum)
.map(object => object.payload)
)
);
I thought creating an object to store all the subjects
would be the best approach, however, this results in all the subjects
inside the object being of a union type. If enum values change for any reason, I would only need to update the enum type, nothing more.