How to Determine the Type of a Message #347
-
Given the following proto:
I would like to use Typescript's union types in a function like this:
The problem is that the right-hand side of the Since I'm generating code from the proto file, would decorators be the way to go here? If so, do I just manually add them to the generated classes? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You can use the message type guards: function publish(connection: Connection, message: ForceValueMessage | UnforceValueMessage){
if(ForceValueMessage.is(message)){
// take one action if the message is a force value
}
else {
// take another action if the message is an unforce value
}
} Or use a proto message UnforceValueMessage {
required string topic = 1;
}
message ForceValueMessage {
required string topic = 1;
required bytes data = 2;
required DataMapItemType itemType = 3;
}
message ValueMessage {
oneof force {
UnforceValueMessage no = 1;
ForceValueMessage yes = 2;
}
} function publish(connection: Connection, message: ValueMessage){
if(message.force.oneofKind === 'yes'){
// take one action if the message is a force value
message.force.yes.data;
}
else if (message.force.oneofKind === 'no'){
// take another action if the message is an unforce value
message.force.no.topic;
}
} |
Beta Was this translation helpful? Give feedback.
You can use the message type guards:
Or use a proto
oneof
: