or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cli-tool.mdindex.mdproto-loading.mdtype-definitions.md
tile.json

type-definitions.mddocs/

Type Definitions

Comprehensive TypeScript type definitions for all Protocol Buffer structures, including messages, services, enums, and method definitions.

Capabilities

Core Data Structures

PackageDefinition

The primary return type containing all loaded Protocol Buffer definitions.

/**
 * Complete definition of a Protocol Buffer package
 * Contains all services, messages, and enums from loaded .proto files
 */
interface PackageDefinition {
  [index: string]: AnyDefinition;
}

type AnyDefinition =
  | ServiceDefinition
  | MessageTypeDefinition<object, object>
  | EnumTypeDefinition;

Usage Examples:

import * as grpc from "@grpc/grpc-js";
import * as protoLoader from "@grpc/proto-loader";

const packageDef = await protoLoader.load("service.proto");
const packageObject = grpc.loadPackageDefinition(packageDef);

// Access services and types
const MyService = packageObject.mypackage.MyService;
const MyMessage = packageObject.mypackage.MyMessage;

Message Type Definitions

MessageTypeDefinition

Type definition for Protocol Buffer messages with serialization/deserialization functions.

/**
 * Type definition for Protocol Buffer messages
 * @template InputType - Type for input objects (permissive)
 * @template OutputType - Type for output objects (with defaults applied)
 */
interface MessageTypeDefinition<InputType, OutputType> extends ProtobufTypeDefinition {
  format: 'Protocol Buffer 3 DescriptorProto';
  serialize: Serialize<InputType>;
  deserialize: Deserialize<OutputType>;
}

interface ProtobufTypeDefinition {
  format: string;
  type: object;
  fileDescriptorProtos: Buffer[];
}

Serialization Interfaces

/**
 * Function type for serializing values to Buffer
 * @template T - Type of value to serialize
 */
interface Serialize<T> {
  (value: T): Buffer;
}

/**
 * Function type for deserializing Buffer to values
 * @template T - Type of value to deserialize to
 */
interface Deserialize<T> {
  (bytes: Buffer): T;
}

Usage Examples:

// Using message serialization
const messageType = packageDef.MyMessage as protoLoader.MessageTypeDefinition<any, any>;
const serialized = messageType.serialize({ field1: "value", field2: 42 });
const deserialized = messageType.deserialize(serialized);

Service Definitions

ServiceDefinition

Collection of method definitions for a gRPC service.

/**
 * Collection of method definitions for a gRPC service
 * Keys are method names, values are MethodDefinition objects
 */
interface ServiceDefinition {
  [index: string]: MethodDefinition<object, object>;
}

MethodDefinition

Complete definition of a gRPC method including streaming, serialization, and metadata.

/**
 * Complete definition of a gRPC method
 * @template RequestType - Type for request messages
 * @template ResponseType - Type for response messages  
 * @template OutputRequestType - Type for deserialized request messages
 * @template OutputResponseType - Type for deserialized response messages
 */
interface MethodDefinition<RequestType, ResponseType, OutputRequestType = RequestType, OutputResponseType = ResponseType> {
  path: string;
  requestStream: boolean;
  responseStream: boolean;
  requestSerialize: Serialize<RequestType>;
  responseSerialize: Serialize<ResponseType>;
  requestDeserialize: Deserialize<OutputRequestType>;
  responseDeserialize: Deserialize<OutputResponseType>;
  originalName?: string;
  requestType: MessageTypeDefinition<RequestType, OutputRequestType>;
  responseType: MessageTypeDefinition<ResponseType, OutputResponseType>;
  options: MethodOptions;
}

Method Options and Metadata

/**
 * Options for gRPC method definitions
 */
interface MethodOptions {
  deprecated: boolean;
  idempotency_level: IdempotencyLevel;
  uninterpreted_option: UninterpretedOption[];
  [k: string]: unknown;
}

/**
 * Enum for gRPC method idempotency levels
 */
enum IdempotencyLevel {
  IDEMPOTENCY_UNKNOWN = 'IDEMPOTENCY_UNKNOWN',
  NO_SIDE_EFFECTS = 'NO_SIDE_EFFECTS',
  IDEMPOTENT = 'IDEMPOTENT'
}

/**
 * Uninterpreted option for method options
 */
interface UninterpretedOption {
  name?: NamePart[];
  identifier_value?: string;
  positive_int_value?: number;
  negative_int_value?: number;
  double_value?: number;
  string_value?: string;
  aggregate_value?: string;
}

/**
 * Part of an option name for method options
 */
interface NamePart {
  name_part: string;
  is_extension: boolean;
}

Enum Definitions

EnumTypeDefinition

Type definition for Protocol Buffer enums.

/**
 * Type definition for Protocol Buffer enums
 */
interface EnumTypeDefinition extends ProtobufTypeDefinition {
  format: 'Protocol Buffer 3 EnumDescriptorProto';
}

Google Protobuf Any Support

AnyExtension

Interface for objects converted to/from google.protobuf.Any messages.

/**
 * Interface for objects converted to/from google.protobuf.Any messages
 * Used with code generated by the proto-loader-gen-types tool
 */
interface AnyExtension {
  /**
   * The fully qualified name of the message type that this object represents,
   * possibly including a URL prefix.
   */
  '@type': string;
}

/**
 * Type guard to check if object is AnyExtension
 * @param obj - Object to check
 * @returns true if object has @type property with string value
 */
function isAnyExtension(obj: object): obj is AnyExtension;

Usage Examples:

import { isAnyExtension, AnyExtension } from "@grpc/proto-loader";

// Processing Any messages
function handleAnyMessage(message: unknown) {
  if (typeof message === 'object' && message !== null && isAnyExtension(message)) {
    switch (message['@type']) {
      case 'type.googleapis.com/mypackage.UserMessage':
        handleUserMessage(message as AnyExtension & UserMessage);
        break;
      case 'type.googleapis.com/mypackage.OrderMessage':
        handleOrderMessage(message as AnyExtension & OrderMessage);
        break;
      default:
        console.log('Unknown message type:', message['@type']);
    }
  }
}

Re-exported Types

Long

Re-exported Long class for handling 64-bit integers.

/**
 * Long integer type for handling 64-bit integers
 * Re-exported from 'long' package for convenience
 */
export { Long } from "long";

Options

Re-exported Options interface from utility module.

/**
 * Configuration options for loading .proto files
 * Re-exported from util module
 */
export { Options } from "./util";

Protobuf.js Module Augmentations

The package extends protobuf.js types with additional descriptor methods for working with Protocol Buffer descriptors:

declare module 'protobufjs' {
  interface Type {
    /**
     * Converts this message type to a descriptor
     * @param protoVersion Protocol Buffer version (typically "proto3")
     * @returns Message descriptor with type information
     */
    toDescriptor(
      protoVersion: string
    ): Protobuf.Message<descriptor.IDescriptorProto> & descriptor.IDescriptorProto;
  }

  interface RootConstructor {
    new (options?: Options): Root;
    /**
     * Creates a Root instance from a FileDescriptorSet
     * @param descriptorSet File descriptor set in various formats
     * @returns Root instance with loaded definitions
     */
    fromDescriptor(
      descriptorSet: descriptor.IFileDescriptorSet | Protobuf.Reader | Uint8Array
    ): Root;
    /**
     * Creates a Root instance from JSON namespace
     * @param json JSON namespace representation
     * @param root Optional existing root to extend
     * @returns Root instance with loaded definitions
     */
    fromJSON(json: Protobuf.INamespace, root?: Root): Root;
  }

  interface Root {
    /**
     * Converts this root to a file descriptor set
     * @param protoVersion Protocol Buffer version (typically "proto3")
     * @returns File descriptor set containing all definitions
     */
    toDescriptor(
      protoVersion: string
    ): Protobuf.Message<descriptor.IFileDescriptorSet> & descriptor.IFileDescriptorSet;
  }

  interface Enum {
    /**
     * Converts this enum type to a descriptor
     * @param protoVersion Protocol Buffer version (typically "proto3")
     * @returns Enum descriptor with type information
     */
    toDescriptor(
      protoVersion: string
    ): Protobuf.Message<descriptor.IEnumDescriptorProto> & descriptor.IEnumDescriptorProto;
  }
}

These augmentations enable proto-loader to work seamlessly with protobuf.js by adding descriptor conversion methods that are essential for creating gRPC-compatible package definitions.

Type Usage Patterns

Type-Safe Service Implementation

import * as grpc from "@grpc/grpc-js";
import * as protoLoader from "@grpc/proto-loader";

const packageDef = await protoLoader.load("service.proto");
const serviceObj = grpc.loadPackageDefinition(packageDef);

// Type-safe server implementation
const server = new grpc.Server();
server.addService(serviceObj.MyService.service, {
  myMethod: (call, callback) => {
    // call.request is typed based on the proto definition
    const response = { message: `Hello ${call.request.name}` };
    callback(null, response);
  }
});

Working with Message Types

// Access message type definition
const MessageType = packageDef.MyMessage as protoLoader.MessageTypeDefinition<any, any>;

// Create and serialize message
const message = { field1: "value", field2: 42 };
const buffer = MessageType.serialize(message);

// Deserialize message
const deserializedMessage = MessageType.deserialize(buffer);