Complex object interface

Sometimes I get an object CoolStuff from api. It has two kinds. I try using discriminated unions. type CoolStuff = {type: 1, goodshit: ...}| {type: 2, badshit: ...} And I have two Components for each of them. I am so sure in component 1, the corresponding type will be 1. I use react query to fetch the CoolStuff. But I don't know how to cast it (or any other good way to make ts system happy)
12 Replies
Neto
Neto2y ago
as type is common between them
Neto
Neto2y ago
if you check fist, then deal with the rest of it
Neto
Neto2y ago
gray0531
gray0531OP2y ago
Yap, by using type guard , the object can fit the type. But ,how can I use this skill in react component. Not inside some function. I wish for A variable with correct type, and no need to use guard , every time I use it.
Neto
Neto2y ago
if(_.type === 1){
return <Component1/>
}

return <Component2/>
if(_.type === 1){
return <Component1/>
}

return <Component2/>
gray0531
gray0531OP2y ago
This is so dope, but I do fetch inside the poohheh want to ask, if you were me, would you use descriminated union in the case? Addon: the goodXxx or badXxx keys related to the type is more than one in my real case.
Neto
Neto2y ago
im not a fan of unions because either way you have to specify somewhere
gray0531
gray0531OP2y ago
Thanks man, so CoolStuff!.goodshit is common usage, right?
Neto
Neto2y ago
people tend to line deterministic code unions are the opposite
gray0531
gray0531OP2y ago
Sorry, I don't get the point of line deterministic code. Is that means people prefer define two specific type for each of them?
Neto
Neto2y ago
if you have a string or a number you have to check later if is one or the other you can't know the data type without checking
gray0531
gray0531OP2y ago
So much confident right now I try to unleashed the power of type. But lack of solid knowledge. Appreciate a lot
Want results from more Discord servers?
Add your server