How to set some mutual exclusion objects in a message

46 views
Skip to first unread message

Ann Lin

unread,
Jun 8, 2022, 4:26:41 AM6/8/22
to Protocol Buffers
Hello:

I'm a Typescript developer and trying to use protobuf between Typescript and Python.

I have to translate several Typescripts interface below to proto3 messages:

```typescript
enum CommandType {
    'Run',
    'Sleep',
    'Read'
}

interface RunCommand {
    commandType: CommandType.Run;
    destination: string;
}

interface SleepCommand {
    commandType: CommandType.Sleep;
    time: number;
}

interface ReadCommand {
    commandType: CommandType.Read;
    book: string
}

type Command = RunCommand | SleepCommand | EatCommand;
```

Tye type `Command` is a message in my .proto like:

```proto3
syntax = "proto3"

enum CommandType {
    RUN = 0;
    SLEEP = 1;
    READ = 2;
}

message Command {
    CommandType commandType = 0;
    ...
}
```

How can I set the rest properties of the message `Command`?

Gary Peck

unread,
Jun 8, 2022, 11:54:26 AM6/8/22
to Protocol Buffers
One way to model this in protobuf is using `oneof`, in which case you don't even really need the enum:

```proto
syntax = "proto3"

message RunCommand {
    string destination = 1;
}

message SleepCommand {
    int32 time = 1;
}

message ReadCommand {
    string book = 1;
}

message Command {
    oneof command_type {
        RunCommand run = 1;
        SleepCommand sleep = 2;
        ReadCommand read = 3;
    }
}
```

Gary
Reply all
Reply to author
Forward
0 new messages