peggy-types
v1.0.0
Published
Automatically extract TypeScript type definitions from Peggy/PEG.js grammars
Maintainers
Readme
peggy-types
Automatically extract TypeScript type definitions from Peggy (PEG.js) grammars.
Feed it a .pegjs grammar string, get back clean, exported TypeScript types — including spreads, tuples, unions, recursive types, mapped types, and more.
Install
npm install peggy-typesUsage
import { PeggyToTsCompiler } from "peggy-types";
const grammar = `
data_type
= dt:(character_string_type / numeric_type) {
return { ...dt, scopeLoc: location() }
}
character_string_type = k:"VARCHAR" { return { keyword: k } }
numeric_type = k:"INT" { return { keyword: k } }
`;
const compiler = new PeggyToTsCompiler(grammar);
const types = await compiler.getTypes();
console.log(types);Output:
import type { LocationRange } from "peggy";
export type character_string_type = {
keyword: "VARCHAR";
};
export type numeric_type = {
keyword: "INT";
};
export type data_type = {
scopeLoc: LocationRange;
} & (character_string_type | numeric_type);What it handles
- Object literals — properties are extracted as typed fields
- Spread expressions —
{ ...dt, extra: true }produces intersection types (& T) - Tuples —
return [true, file]produces[true, string], not(string | boolean)[] - Indexed access —
file[0]resolves to the correct tuple element type - Unions — multiple alternatives with different shapes merge into discriminated-union-style types with optional fields
- Recursive / self-referencing rules — handled with an
unknownsentinel to prevent infinite loops as constliterals —'hex_string' as constpreserves the literal type"hex_string"- Case-insensitive keywords —
"WHERE"istays"WHERE", notstring - Deduplication — identical union alternatives are collapsed
- Reserved word escaping — a rule named
numberbecomesexport type number_ = ... - Preamble / initializer injection — helper functions in
{ ... }blocks are injected into the type resolver so calls likecreateList(head, tail)resolve correctly instead of falling back toany LocationRange/Locationimports — automatically added from"peggy"only when referenced
API
new PeggyToTsCompiler(grammarString: string)
Parses the grammar and prepares the internal type resolver.
.getTypes(): Promise<string>
Resolves all rule types and returns the formatted TypeScript output string (formatted with Prettier).
License
MIT
