4

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?

Thinking
  • 41
  • 1
  • 2

1 Answers1

3

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.

Timo Stamm
  • 610
  • 4
  • 10
  • What pros does your lib have? Why should we use it instead of https://github.com/protobufjs/protobuf.js and https://github.com/stephenh/ts-proto ? – Viacheslav Dobromyslov Jan 17 '21 at 17:49
  • 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. – Timo Stamm Jan 18 '21 at 09:25