ts-proto icon indicating copy to clipboard operation
ts-proto copied to clipboard

How to access field when using oneof=structs?

Open dannnnthemannnn opened this issue 3 years ago • 3 comments

Curious are there any utilities or anything to type safely convert the oneof.property to whichever case matches?

In my IDE if I try to access the oneof field it only gives me access to the $case field. I'm guessing I can create a function that will look at that $case field and return the object casted to the right type based on the $case field. Curious if there is an easier way to do that than writing my own function whenever I use oneof. Or like a built in generated helper the enumToJson() functions.

dannnnthemannnn avatar Jun 07 '22 23:06 dannnnthemannnn

Thinking about this more, maybe the question doesnt make any sense. I just need to do a switch statement which will identify the correct type and then I handle them accordingly. Or if I know that it has to be a specific type (like based off of another enum field), then I could just cast it. I'll leave open in case anyone has any insight that I'm not thinking about, but feel free to close if theres nothing else interesting to discuss.

dannnnthemannnn avatar Jun 07 '22 23:06 dannnnthemannnn

For anyone following along the way I am access it now is:

// Error because we didn't verify it was the right $case
myObj.oneOfField.myCaseString.whateverField; 

// Not an error since we verified that the $case matches what we expect. 
myObj.oneOfField?.$case == "myCaseString" && myObj.oneOfField.myCaseString.whateverField;

Same applies to a switch where the compiler knows which type it was after the case matches $case.

dannnnthemannnn avatar Jun 07 '22 23:06 dannnnthemannnn

These are discriminated unions, unfortunately the best way requires a bit of boilerplate to create type guard functions. https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates

tannera-cargill avatar Jun 10 '22 14:06 tannera-cargill