Registry / serialization / ts-poet

ts-poet

JSON →
library6.12.0jsnpmunverified

ts-poet is a specialized code generation DSL (Domain Specific Language) for TypeScript, currently at version 6.12.0. It distinguishes itself by leveraging TypeScript's template literals to provide an intuitive, string-based approach to code generation, sidestepping the complexities of direct Abstract Syntax Tree (AST) manipulation. Its core strength lies in automatic import management, intelligently collecting and emitting necessary `import` statements, resolving symbol collisions, and simplifying conditional output. ts-poet also integrates `dprint-node` for fast and 'prettier-ish' code formatting, a significant differentiator from many generators that output unformatted or poorly formatted code. While inspired by JavaPoet's builder patterns in its earlier v1/v2 releases, the library has since evolved to a more streamlined, template-literal-centric API, making it highly adaptable for generating code from arbitrary schemas or user-defined inputs. The project maintains an active development status with consistent updates to support modern TypeScript features and ecosystem changes.

npm install ts-poet
INSTALL
IMPORT
SIG · TS-POET
T
ts-poet
serializationjavascriptv6.12.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Code
import { Code, imp, def } from 'ts-poet';
const { Code, imp, def } = require('ts-poet');
The primary entry point for generating code using template literals. `ts-poet` is an ESM-first library and should be imported using ES module syntax.
imp
import { imp } from 'ts-poet';
`imp` is used to declare external imports. It handles named, default, renamed, and type imports, and automatically collects them for the final output. E.g., `imp('Symbol@module')`, `imp('t:Type@module')`.
def
import { def } from 'ts-poet';
`def` marks an internally defined symbol in the generated code. It is crucial for `ts-poet` to recognize local declarations and correctly avoid import collisions by renaming imported symbols if necessary. E.g., `class ${def('MyClass')} { ... }`.
conditionalOutput
import { conditionalOutput } from 'ts-poet';
Allows sections of code to be included in the output only if they are 'used' elsewhere in the generated code, useful for utility functions or helper methods that might not always be required.

This quickstart demonstrates `ts-poet` generating a TypeScript class with an interface, methods, and RxJS imports. It showcases `Code` template literals, automatic import management with `imp` and `def`, and `dprint-node` for formatting.

import { Code, imp, def } from 'ts-poet'; import * as fs from 'node:fs/promises'; // Define an external import (e.g., from a utility library) const Observable = imp('Observable@rxjs'); const Subject = imp('Subject@rxjs'); // Generate a TypeScript class with methods and imported types const generatedCode = Code` export interface ${def('GreeterOptions')} { name: string; greetingMessage?: string; } /** * A class that greets people using RxJS Observables. */ export class ${def('Greeter')} { private readonly name: string; private readonly greetingSource = new ${Subject}<string>(); /** * Observable stream of greetings. */ public readonly greetings = this.greetingSource.asObservable(); constructor(options: ${GreeterOptions}) { this.name = options.name; if (options.greetingMessage) { this.greetingSource.next(options.greetingMessage); } } /** * Emits a personalized greeting. */ sayHello(): void { this.greetingSource.next(`Hello, ${this.name}!`); } /** * Returns an Observable that completes after a single greeting. */ greetOnce(): ${Observable}<string> { return new ${Observable}(observer => { observer.next(`One-time greeting for ${this.name}.`); observer.complete(); }); } } `; async function main() { const output = generatedCode.toString({ // Optionally configure dprint-node formatting options dprintOptions: { indentWidth: 2, lineWidth: 100 } }); console.log('--- Generated Code ---'); console.log(output); // For real-world use, save to a file await fs.writeFile('generated-greeter.ts', output); console.log('\nGenerated code written to generated-greeter.ts'); } main().catch(console.error);
Debug
Known issues
breakingThe API underwent a significant shift after v2/v3.0. Earlier versions were heavily inspired by JavaPoet, featuring a builder-style API (e.g., `addFunction()`, `addProperty()`). Current versions (v3.0+) transition to a more idiomatic TypeScript template literal DSL. Migrating from very old versions requires a complete rewrite of generation logic.
fix
Rewrite code generation logic to use the `Code` template literal tag, `imp` for imports, and `def` for local definitions, as detailed in the current documentation.
affects: <3.0
gotchats-poet uses `dprint-node` for automatic code formatting by default. While it aims for 'prettier-ish' output, subtle differences in formatting rules can lead to discrepancies if your project heavily relies on Prettier or has a custom `.prettierrc` configuration. This can result in conflicting formatting upon generation or linting errors.
fix
Either configure dprint-node via `Code.toString({ dprintOptions: { ... } })` to match your desired style or create a `.dprint.json` file in your project root. Alternatively, you can disable `ts-poet`'s internal formatting and run a separate Prettier pass on the generated files.
affects: >=3.0
gotcha`ts-poet`'s `imp` function handles different import styles (named, default, type, renamed). However, specific edge cases, especially related to Node.js's `esModuleInterop` compiler option and certain libraries (e.g., `protobufjs` as noted in `ts-poet`'s README), might require explicit import syntax adjustments or aliasing within `imp` to resolve correctly.
fix
For problematic imports, consult `ts-poet`'s documentation on `imp`'s advanced usage. You might need to use `imp('Namespace.Member@module')` or `imp('Default:Alias@module')` to guide `ts-poet` in generating the correct import statement for the target environment and TypeScript configuration.
affects: >=3.0
Errors
Common errors & fixes
Cannot find module 'ts-poet' or its corresponding type declarations.
Incorrect module resolution (e.g., attempting CommonJS `require` in an ESM project) or `ts-poet` not being correctly installed or linked in a monorepo.
fix
Ensure your project is configured for ES modules (`"type": "module"` in `package.json` or `.mjs` extension) and use `import { ... } from 'ts-poet';`. Verify `ts-poet` is in `dependencies` and installed via `npm install` or `yarn add`.
Error: dprint-node was not found (or another dprint-node related error during `toString()` call).
The `dprint-node` package, which `ts-poet` relies on for formatting, is not installed or accessible in the environment where code generation is being run.
fix
Install `dprint-node` as a dependency: `npm install dprint-node` or `yarn add dprint-node`. Ensure it's resolvable in your project's `node_modules`.
Type 'Code' is not assignable to type 'string'.
Attempting to use a `Code` instance (the result of a `Code` tagged template literal) directly where a string is expected, without calling `.toString()` on it.
fix
Always call `.toString()` on a `Code` instance to get the final generated string output. E.g., `const output = generatedCode.toString();`.
Property 'x' does not exist on type 'Code'.
Incorrectly trying to access properties or methods on the `Code` tag or its return value, or misusing template literal interpolations that are not valid `ts-poet` primitives.
fix
The `Code` function is a tagged template literal. Its arguments should primarily be `imp()` calls, `def()` calls, `Code` instances, or raw strings/numbers. Avoid complex logic or direct object access within the template literal; extract it outside if necessary.
Upgrade
Version history
6.12.0latest on npm
Audit
Dependencies
dprint-noderequiredUsed for fast and 'prettier-ish' formatting of generated TypeScript code. It's a crucial runtime dependency if formatting is enabled (which it is by default in `Code.toString()`).
Agent activity
14 hits · last 30 days
node
12
OpenAI (training)
1
Resources
ts-poet — npm install ts-poet · libregistry