grpc-web icon indicating copy to clipboard operation
grpc-web copied to clipboard

Improve Typescript oneof generated types

Open HenriBeck opened this issue 3 years ago • 3 comments

When started using grpcweb, we found the typings of a oneof statement rather outdated and not type-safe.

Problems

With the current typings being an object with just optional keys, we found it to be not very developer-friendly.

type Type = {
  email?: string,
  password?: string,
};

The above type doesn't make it clear that the email or password can be set, and also doesn't prevent any misuse of the data.

Solution

The best typing that we could come up with was the following:

enum OneOfCase {
  NOT_SET = 0,
  EMAIL = 1,
  PASSWORD = 2
}

type Type =
  | {
      case: OneOfCase.NOT_SET;
    }
  | {
      case: OneOfCase.EMAIL;
      email: string;
    }
  | {
      case: OneOfCase.PASSWORD;
      password: string;
    };

These typings improve a few things:

  • Improves the switch/case handling as it only allows to access the correct fields
  • Makes the oneof intent clearer as only one field could ever be set
  • Added benefit is that an exhaustion check is possible now that every case has been handled

Would it be possible to change these types to something more modern utilizing some newer TS features?

Full example found here: https://codesandbox.io/s/youthful-surf-j0mz3?file=/src/index.ts

HenriBeck avatar Sep 01 '20 15:09 HenriBeck

If anyone else stumbles upon this, until this issue is resolved, https://github.com/stephenh/ts-proto implements oneof in the exact way, as @HenriBeck suggests.

Raiondesu avatar Sep 16 '20 16:09 Raiondesu

@Raiondesu @HenriBeck We have the same issue. But does the https://github.com/stephenh/ts-proto library work with grpc-web? Meaning, can you generate your stubs using the ts-proto library, but then use them with the grpc-web framework?

Sollimann avatar Dec 06 '22 12:12 Sollimann