I am Software Developer, currently interested in static type languages (TypeScript, Elm, ReScript) mostly in the frontend land, but working actively in Python also. I am available for mentoring.
It's works exactly as union. Union says one or another let's say A | B so if you don't know yet which of these two your value represents you cannot use it's properties. Let's say A has property name but B has no such then TS is properly securing from the runtime error when you would want to use name on object without name.
In order to know if we have A or B at this point we need to set a type guard so generally some condition.
When you consider sets as types then by union let's say C you create a type with two objects A, B, the value of C can be either A or B never A and B in the same time.
If you want to have all properties of two objects then you want a product type of them which can be achieved by &, so A & B will create a type which considers all fields of both types.
OK, I realized it shortly after posting. However, how would you ever handle a typical case like a state reducer (in Redux for example) where your payloads can contain different subsets of data but they occur via events?
I am Software Developer, currently interested in static type languages (TypeScript, Elm, ReScript) mostly in the frontend land, but working actively in Python also. I am available for mentoring.
We need to join type with prop, in other way TS is not able to understand what property is in add action or update action. Such construct is known as sum type or discriminated union.
It's works exactly as union. Union says one or another let's say
A | B
so if you don't know yet which of these two your value represents you cannot use it's properties. Let's say A has property name but B has no such then TS is properly securing from the runtime error when you would want to use name on object without name.In order to know if we have A or B at this point we need to set a type guard so generally some condition.
When you consider sets as types then by union let's say C you create a type with two objects A, B, the value of C can be either A or B never A and B in the same time.
If you want to have all properties of two objects then you want a product type of them which can be achieved by &, so A & B will create a type which considers all fields of both types.
OK, I realized it shortly after posting. However, how would you ever handle a typical case like a state reducer (in Redux for example) where your payloads can contain different subsets of data but they occur via events?
TS always warns that propB would not be available in type ADD being dispatched and propA not being available in UPDATE being dispatched.
So the proper typying of this case is:
We need to join type with prop, in other way TS is not able to understand what property is in add action or update action. Such construct is known as sum type or discriminated union.
Thanks, I'll try this