timostamm / protobuf-ts

Protobuf and RPC for TypeScript
Apache License 2.0
1.1k stars 131 forks source link

Is this compiling error could be turned off by Typescript or Option in protobuf-ts #613

Closed shawncao closed 11 months ago

shawncao commented 12 months ago

Hi,

This project looks promising, so try it out to migrate existing PROTOC common to this plugin.

I just hit a compile error as stated below:

Part of proto def:

syntax = "proto3";
package nebula.service;
...
message QueryRequest {
  string table = 1;

  // at the top tree as filter - it can be only one, either AND or OR
  oneof filter {
    PredicateAnd filterA = 2;
    PredicateOr filterO = 3;
  }
 ...
}

The generated code looks like this

    internalBinaryWrite(message: QueryRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
        /* string table = 1; */
        if (message.table !== "")
            writer.tag(1, WireType.LengthDelimited).string(message.table);
        /* nebula.service.PredicateAnd filterA = 2; */
        if (message.filter.oneofKind === "filterA")
            PredicateAnd.internalBinaryWrite(message.filter.filterA, writer.tag(2, WireType.LengthDelimited).fork(), options).join();

And compiling error looks like this:

$ npx protoc --ts_out=src/gen --ts_opt=client_grpc1 --proto_path=src nebula.proto && tsc
src/gen/nebula.ts:1643:61 - error TS2339: Property 'filterA' does not exist on type '{ oneofKind: "filterA"; filterA: PredicateAnd; } | { oneofKind: undefined; }'.
  Property 'filterA' does not exist on type '{ oneofKind: undefined; }'.

1643             PredicateAnd.internalBinaryWrite(message.filter.filterA, writer.tag(2, WireType.LengthDelimited).fork(), options).join();

I understand, the generated code may be legit, just Typescript needs option to pass the check, but I'm not sure, as I seem can't find an option for that. Love to check here if anybody knows how to fix this?

Thanks!

timostamm commented 11 months ago

See https://github.com/timostamm/protobuf-ts/blob/main/MANUAL.md#oneof-representation 🙂

shawncao commented 11 months ago

This is awesome, thank you so much! The fix is simply to flip it to "strictNullChecks": true, in tsconfig

As a temp fix yesterday, I changed the oneof field to two optional fields, can't tell if it has much disadvantage, still scratching my head as to why I used oneof in the first place, haha~