Protocol Buffer Compiler for TypeScript

0.8.7 · active · verified Sun Apr 19

protoc-gen-ts is a `protoc` plugin that generates plain TypeScript source files from Protocol Buffer `.proto` definitions, effectively replacing separate `.d.ts` declaration files. It is actively maintained, with the current stable version being `0.8.7`, and new features/fixes are delivered through frequent minor releases. A key differentiator is its direct TypeScript output which eliminates common prefixes (e.g., `getField`) and exposes fields as standard getters/setters, along with `fromObject` and `toObject` methods for robust bidirectional mapping between JSON and message instances, supporting deep structures without runtime type reflection. It offers native support for gRPC Node (`@grpc/grpc-js`) and gRPC Web, including options for promise-based RPC calls. Messages defined within a `package` directive in the `.proto` file are by default encapsulated within a TypeScript namespace, though this behavior can be toggled.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create, serialize, and deserialize a Protocol Buffer message using the generated TypeScript classes. It also illustrates the convenient `fromObject` and `toObject` methods for JSON interoperability.

import { Change, Kind, Author } from './myproto_pb'; // Assumes protoc-gen-ts generated './myproto_pb.ts'

// Construct a message instance
const author = new Author({
    name: 'mary poppins',
    role: 'maintainer'
});

const change = new Change({
    kind: Kind.UPDATED,
    patch: '@@ -7,11 +7,15 @@',
    tags: ['no prefix', 'as is'],
    name: 'patch for typescript 4.5',
    author: author
});

// Serialize to bytes (Uint8Array)
const bytes: Uint8Array = change.serialize();

console.log('Serialized bytes:', bytes);

// Deserialize from bytes back into a message instance
const receivedChange: Change = Change.deserialize(bytes);

console.log('Deserialized Change object:', receivedChange);
console.log('Kind:', receivedChange.kind === Kind.UPDATED); // true
console.log('Author name:', receivedChange.author?.name); // mary poppins

// Using fromObject for easier JSON-to-message mapping
const jsonChange = Change.fromObject({
    kind: Kind.DELETED,
    patch: 'deleted line',
    tags: ['cleanup'],
    id: '12345',
    author: {
        name: 'john doe',
        role: 'contributor'
    }
});

console.log('Change from JSON:', jsonChange.toObject());
console.log('Author from JSON is an Author instance:', jsonChange.author instanceof Author);

view raw JSON →