首页 > 解决方案 > 如何使用 Protobuf 生成的类作为 TypeScript 的类型?

问题描述

抱歉,如果这是基本的,但我是 TypeScript 的新手并且想知道......假设我生成了一个.js名为的 Protobuf 文件

request_pb.js

而且我想在传递一个值时将生成的类之一合并为 TypeScript 类型,例如类似于...


const req = require('../build/gen/request_pb');

/**
 * check if incoming request is valid
 * @param data
 */
function validateRequest(data: req.Request) { // TODO: how to include type information?
    return data.hasStartDateEt() && data.hasEndDateEt();
}

我目前正在

“找不到命名空间‘req’”

这到底是什么意思,我该怎么办?

标签: typescript

解决方案


我使用将 TypeScript 定义文件生成到相同的构建目录中

$ protoc --proto_path=schemas --js_out=import_style=commonjs,binary:build/gen --ts_out=build/gen schemas/*.proto schemas/enums/*.proto 

ts-protoc-gen包(https://www.npmjs.com/package/ts-protoc-gen)。

然后我可以使用导入类型

import account_statement_req from '../build/gen/account_statement_request_pb';

推荐阅读