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

Bad TS types for proto3 optional fields #295

Open
krpecd opened this issue Jan 20, 2022 · 1 comment
Open

Bad TS types for proto3 optional fields #295

krpecd opened this issue Jan 20, 2022 · 1 comment

Comments

@krpecd
Copy link

krpecd commented Jan 20, 2022

When a proto file has an optional field:

syntax = "proto3";

package example;

message Example 
{
  optional string optional_field = 1;
}

It generates this TS definitions

// package: example
// file: proto/example/example.proto

import * as jspb from "google-protobuf";

export class Example extends jspb.Message {
  hasOptionalField(): boolean;
  clearOptionalField(): void;
  getOptionalField(): string;
  setOptionalField(value: string): void;

  serializeBinary(): Uint8Array;
  toObject(includeInstance?: boolean): Example.AsObject;
  static toObject(includeInstance: boolean, msg: Example): Example.AsObject;
  static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
  static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
  static serializeBinaryToWriter(message: Example, writer: jspb.BinaryWriter): void;
  static deserializeBinary(bytes: Uint8Array): Example;
  static deserializeBinaryFromReader(message: Example, reader: jspb.BinaryReader): Example;
}

export namespace Example {
  export type AsObject = {
    optionalField: string,
  }
}

I think the namespace should be in this format:

export namespace Example {
  export type AsObject = {
    optionalField?: string,
  }
}

I can find out if the field is in the message by using hasOptionalField method. But TS check is not working as expected.

const optionalField: string = message.toObject().optionalField; // this should throw type Error
@yzhaoa
Copy link

yzhaoa commented Apr 20, 2023

toObject() for proto3 optional fields are still generated like so by the protoc js compiler:

    optionalField: jspb.Message.getFieldWithDefault(msg, 1, ""),

Note the Default part.

This conforms with the google-protobuf getter APIs and getter semantics in other languages. Please do not change this behavior with toObject().

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

No branches or pull requests

2 participants