Marc Gelfo
Marc Gelfo

Reputation: 91

protobuf.js pbts: Generating typescript types from .proto without null | undefined

I'm using pbts to generate typescript declaration files for a large protobuf library.

The problem is that the pbts output makes every property undefined or null, e.g.

interface IMyThing { myProp?: string | null; } and what I want is:

interface IMyThing { myProp: string; }

The actual protobuf definitions are NOT optional. They look like:

message MyThing { string myProp = 1; }

Is there some flag or way to adjust the source code of pbts or post-process its output, so that I can remove these incorrect undefined/null attributes?

Upvotes: 2

Views: 2024

Answers (2)

Timo Stamm
Timo Stamm

Reputation: 750

For proto3 syntax:

While message fields are always optional, scalar fields like string are always required.

So myProp: string would be the correct representation.

In the binary wire format, an empty string is not written at all. But the generated code should set the default value "" when reading from binary data that does not include data for this field.

There is a new experimental feature in protobuf 3.12.0 that allows making a string field optional. Then the signature should be myProp?: string or myProp: string | undefined.

I recommend having a look at ts-proto or (this is a shameless plug for my implementation) protobuf-ts.

Upvotes: 0

Marc Gelfo
Marc Gelfo

Reputation: 91

UPDATE: Since all messages in protobuf 3 are optional, this is by design.

Upvotes: 3

Related Questions