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
as
type
is common between themif you check fist, then deal with the rest of it
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.
This is so dope, but I do fetch inside the 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.
im not a fan of unions
because either way you have to specify somewhere
Thanks man, so CoolStuff!.goodshit is common usage, right?
people tend to line deterministic code
unions are the opposite
Sorry, I don't get the point of line deterministic code.
Is that means people prefer define two specific type for each of them?
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
So much confident right now
I try to unleashed the power of type.
But lack of solid knowledge.
Appreciate a lot