protobuf.js icon indicating copy to clipboard operation
protobuf.js copied to clipboard

[pbts] oneof should use discriminating union types

Open masad-frost opened this issue 2 years ago • 1 comments

protobuf.js version: 6.11.x

Given a proto

message Command {
  oneof body {
    string error = 1;
    string result = 2;
  }
}

It should output

type ICommand =
  | {
    body: 'error';
    error: string;
  }
  | {
    body: 'result'
    result: string;
  }

Currently it does the following

interface ICommand {
  body: 'error' | 'result';
  error?: string | null; 
  result?: string | null;
}

masad-frost avatar Sep 03 '21 02:09 masad-frost

I think this becomes quite complex if there are multiple oneof fields on a message.

I think ideally the discriminated union should be inside the body property, and would need to have a form that was something like

type OneOfChoice<Type extends string, T> = { type: Key, value: T }

Which would result in something like

interface ICommand {
  body: OneOfChoice<'error', {error: string}> | OneOfChoice<'result', {result: string}>
}

glenjamin avatar Feb 23 '22 11:02 glenjamin