Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Typescript oneof generated types #947

Open
HenriBeck opened this issue Sep 1, 2020 · 3 comments
Open

Improve Typescript oneof generated types #947

HenriBeck opened this issue Sep 1, 2020 · 3 comments

Comments

@HenriBeck
Copy link

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

@Raiondesu
Copy link

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
Copy link

Sollimann commented Dec 6, 2022

@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
Copy link
Collaborator

FYI - I'm guessing #1445 might be related here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants