Understand default values and unset fields
mainFollowing Protobuf rules, ts-proto cannot distinguish between a field being explicitly set to its default value and a field being unset.
- Decoding:
ts-protoalways returns default values for unset fields (e.g.,''forstring,0fornumber). - Encoding:
ts-protoomits unset fields and fields set to their default values from the binary output. - JSON (
fromJSON/toJSON):- Use
fromJSONto normalize input, as it will initialize default values for missing fields. toJSONnormalizes messages by omitting unset fields and fields set to their default values.
- Use
If you need to detect if a primitive field was actually set, use Wrapper Types.
syntax = "proto3";
message Foo {
string bar = 1;
}// Decoding an empty buffer
Foo.decode(protobufBytes); // => { bar: '' }
// Encoding a default value
Foo.encode({ bar: "" }); // => { }, writes an empty Foo object
// JSON Normalization
Foo.fromJSON({}); // => { bar: '' }
Foo.toJSON({ bar: "" }); // => { }