How to use google.protobuf.Any type in typescript?
Asked Answered
S

1

6

1.the protocol buffer 3 file test.proto

option go_package = ".;apps";
package apps;

message ShardKvMap{
  map<string, google.protobuf.Any> data = 1;
}

2.i use grpc-web build .ts file

protoc -I=$DIR test.proto \
  --js_out=import_style=commonjs,binary:$OUT_DIR \
  --grpc-web_out=import_style=typescript,mode=grpcwebtext:$OUT_DIR

3.How to use google.protobuf.Any type in typescript?

Smoulder answered 12/7, 2020 at 8:0 Comment(0)
C
4

I cannot help you with the build-in JS and TS support, but I can tell you how to do it with the protobuf-ts plugin (I am the author).

// this creates an empty new message
let msg = ShardKvMap.create();

// this packs the empty new message into an Any message, 
// and adds it to map under the key "foo":
msg.data["foo"] = Any.pack(msg, ShardKvMap);

As far as I know, protobuf-ts is the only library out there for JavaScript / TypeScript that fully supports google.protobuf.Any, including JSON format. Here is the section about Any support in the manual.

Cachou answered 7/9, 2020 at 14:55 Comment(2)
What pros does your lib have? Why should we use it instead of github.com/protobufjs/protobuf.js and github.com/stephenh/ts-proto ?Reata
I wrote protobuf-ts because ts-proto and protobuf.js's support for well-known-types, code size in a web application and conformance with the protobuf spec was not sufficient for me.Cachou

© 2022 - 2025 — McMap. All rights reserved.