如何在Proto3(gRPC)的Protocol Buffer文件中表示嵌套数组?
解决方案
Protobuf本身没有原生的二维数组类型,你之前的写法生成对象数组是因为嵌套了带命名字段的内部Message。要生成对应TypeScript的number[][]类型,有两种可行方案:
方案一:调整Protobuf定义 + 生成工具配置
使用嵌套Message,同时通过生成工具的配置让嵌套Message直接映射为数组(以常用的protobuf-ts为例):
Protobuf文件内容
syntax = "proto3"; message RouteShape { string type = 1; repeated DoubleArray coordinates = 2; } // 定义承载一维数组的Message message DoubleArray { repeated double items = 1; }
配置protobuf-ts类型映射
在项目的protobuf-ts.json配置文件中添加规则,将DoubleArray直接映射为number[]:
{ "compileOnSave": false, "protoc": { "path": "./node_modules/.bin/protoc", "args": [] }, "plugins": [ { "name": "ts", "path": "./node_modules/.bin/protoc-gen-ts", "args": [ "--ts_opt=map=DoubleArray:number[]" ] } ] }
配置完成后,生成的TypeScript类型会直接匹配你需要的RouteShape { type: string; coordinates: number[][] }。
方案二:Protobuf原生写法 + TypeScript类型转换
如果不想修改生成工具配置,可以采用简化写法(部分编译器支持),或在TypeScript中手动转换类型:
扩展语法写法(需编译器支持)
部分Protobuf编译器允许直接嵌套repeated字段,写法如下:
syntax = "proto3"; message RouteShape { string type = 1; repeated repeated double coordinates = 2; }
嵌套Message + 手动转换
如果编译器不支持上述扩展语法,仍使用方案一的嵌套Message写法,生成TS后手动转换类型:
// 生成的原始类型 interface GeneratedRouteShape { type: string; coordinates: { items: number[] }[]; } // 转换为目标类型 const convertToRouteShape = (generated: GeneratedRouteShape): RouteShape => ({ type: generated.type, coordinates: generated.coordinates.map(item => item.items) });
内容的提问来源于stack exchange,提问作者Gabriel Lupu
相关产品推荐
相关产品推荐

