首页 > 解决方案 > 如何在打字稿中使用 google.protobuf.Any 类型?

问题描述

1.protocol buffer 3文件test.proto

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

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

2.我使用 grpc-web 构建 .ts 文件

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

3.如何在typescript中使用google.protobuf.Any type?

标签: typescriptprotocol-buffersgrpc-web

解决方案


我无法为您提供内置的 JS 和 TS 支持,但我可以告诉您如何使用protobuf-ts 插件(我是作者)来做到这一点。

// 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);

据我所知,protobuf-ts 是唯一一个完全支持 google.protobuf.Any 的 JavaScript / TypeScript 库,包括 JSON 格式。这是手册中有关任何支持的部分。


推荐阅读