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

Viewed 4063

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?

1 Answers

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.

Related