Making OneOf feature not require strickNullCheck to be enabled. #254
jimmymkude
started this conversation in
Ideas
Replies: 1 comment 1 reply
-
Hey Jimmy, this is a valid workaround, but probably has some drawbacks around It looks like |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I played around with this, and I was eventually was able to get it work with ('strictNullChecks': false) by the changing the generated ts file to use a class to define the undefined oneof object instead of { oneofKind: undefined; }.
Using the docs example:
message OneofExample {
// Only one of (or none of) the fields can be set
oneof result {
int32 value = 1;
string error = 2;
}
}
interface OneofExample {
result: { oneofKind: "value"; value: number; }
| { oneofKind: "error"; error: string; }
| { oneofKind: undefined; };
}
This would change to:
class UndefinedOneOf {
oneofKind: undefined;
}
interface OneofExample {
result: { oneofKind: "value"; value: number; }
| { oneofKind: "error"; error: string; }
| UndefinedOneOf;
}
Now if we handle the undefined case first, it gives us the type guard to narrow down the type. For example, in the generated internalByteWrite function.
if (message.result instanceof UndefinedOneOf)
// Type guard above narrows down scope.
else if (message.result.oneofKind === "value")
// Knows the result type is not undefined.
Number.internalBinaryWrite(message.result.value, writer.tag(4, WireType.LengthDelimited).fork(), options).join();
What are your thoughts?
Beta Was this translation helpful? Give feedback.
All reactions