TypeScript AST Template Generator

2.4.5 · active · verified Tue Apr 21

Talt is a utility library that provides template functions for generating TypeScript Abstract Syntax Tree (AST) nodes programmatically. Inspired by Babel's `@babel/template`, it allows developers to define AST structures using familiar TypeScript syntax within template strings, which are then parsed and transformed into `ts.Node` objects. This significantly simplifies the process of creating and manipulating TypeScript ASTs compared to using the `typescript.factory` API directly. The current stable version is 2.4.5, with releases occurring as needed for bug fixes and feature enhancements, as seen in recent patch versions. Its primary differentiator is the template-based approach, which enhances readability and reduces boilerplate when working with complex AST constructions, especially useful in code transformation, linting, or transpilation tools. It relies on `typescript` as a peer dependency for its AST types and parsing capabilities.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `talt` to generate complex TypeScript AST nodes, including type declarations and expressions with placeholders, and then print them.

import ts from 'typescript';
import { template } from 'talt';

// Create a type node using a template string
const interfaceTypeNode = template.typeNode`
  interface MyInterface {
    id: string;
    createdAt: Date;
  }
`();

// Create an expression node with a placeholder
const mathExpressionTemplate = template.expression`
  (BASE_VALUE * 2) + ${() => ts.factory.createNumericLiteral('10')}
`;

const generatedExpression = mathExpressionTemplate({
  BASE_VALUE: ts.factory.createNumericLiteral('50')
});

// You can then print the generated AST node to verify
const printer = ts.createPrinter({
  newLine: ts.NewLineKind.LineFeed
});
const resultFile = ts.createSourceFile('temp.ts', '', ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
const printedNode = printer.printNode(ts.EmitHint.Unspecified, generatedExpression, resultFile);

console.log('Generated Interface Type Node:\n', printer.printNode(ts.EmitHint.Unspecified, interfaceTypeNode, resultFile));
console.log('Generated Expression Node:\n', printedNode);

view raw JSON →