Skip to main content

What It Is

The Interpreter pattern evaluates sentences in a small language by building a tree of expression nodes — numbers, additions, subtractions — and then walking that tree. A number evaluates to itself; an addition evaluates its two sides and adds them.

In TypeScript the tree is a discriminated union: every node is a plain object with a kind field, and one function switches on that field. Because the union lists every node type, the compiler complains if a case is missing.

It fits small languages: filters, formulas, simple rules. Real languages deserve real parser tools.


Example: A Tiny Calculator

The input 3 + 4 - 2 becomes a tree of number, add and subtract nodes. One call to interpret() on the root evaluates the whole expression.

One tree, one interpret function

parse builds the tree left to right; interpret walks it and prints 3 + 4 - 2 = 5. Supporting * would be one new member of the union plus one new case — the existing ones stay untouched.

Prompt
Write a TypeScript program with the Interpreter pattern: an Expression discriminated union of number, add and subtract nodes, an interpret function that switches on the kind field, and a parse function that turns a string like "3 + 4 - 2" into an expression tree left to right. Interpret the expression and print the equation with its result.
Output: TypeScript file and captured output

When to Use It

Use it when users or configs express logic in a small language of your design: search filters, pricing formulas, validation rules.

Skip it when the “language” is three fixed options (a plain switch is enough) — or a real language (use a parser generator or an existing engine).


Pros and Cons

Pros: the grammar maps one-to-one onto the members of the union; new operations are new members; expression trees can be built, checked and reused.

Cons: grows painful as the grammar grows; parsing itself still has to be written; performance is modest compared to compiled logic.