grpc / grpc-web

gRPC for Web Clients
https://grpc.io
Apache License 2.0
8.6k stars 763 forks source link

Improve Typescript oneof generated types #947

Open HenriBeck opened 4 years ago

HenriBeck commented 4 years ago

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:

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

Raiondesu commented 4 years ago

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.

Sollimann commented 1 year ago

@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?

sampajano commented 3 months ago

FYI - I'm guessing https://github.com/grpc/grpc-web/pull/1445 might be related here.