grpc-web
grpc-web copied to clipboard
Improve Typescript oneof generated types
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
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 @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?