How to Implement the Interpreter Pattern in TypeScript
Implement the Interpreter pattern in TypeScript by modeling a small language as an expression tree, parsing text into it and evaluating it against a context.

The Interpreter pattern represents the sentences of a small language as a tree of objects and gives each node the ability to evaluate itself. You define a grammar, build a class or a node type for each rule, parse text into a tree, and then call interpret on the root with a context that holds variables. It suits small, stable languages that your program needs to read: search filters, discount rules, permission expressions, formulas in a spreadsheet cell, routing rules. It is a poor fit for large languages, where parser generators and compilers do the job better. This post shows how to implement the Interpreter pattern in TypeScript 5.9 on Node.js 24: a grammar for boolean rule expressions, an expression tree, a recursive-descent parser, evaluation with a context, error handling, tests and the limits of the pattern, with the output of each sample.
The tree is a Composite, and the evaluation can be written as a Visitor when you want more than one operation over the same tree. This post keeps evaluation inside the nodes, which is the classic form of Interpreter.
The language
Imagine a rules engine that lets an administrator write conditions as text, for example whether a user may see a feature. The language has variables that name facts about the user, the literals true and false, and the operators and, or and not with parentheses.
admin or (beta and not banned)A grammar for it, in a simple notation, is:
expression = term { "or" term }
term = factor { "and" factor }
factor = "not" factor | "(" expression ")" | "true" | "false" | variablePutting and below or in the grammar gives and higher precedence, which matches ordinary boolean logic. Each grammar rule becomes either a node class or a parser function.
The expression tree
Each node implements one method, interpret, that takes a context, a map of variable values, and returns a boolean.
type Context = Record<string, boolean>;
interface Expression {
interpret(context: Context): boolean;
}
class Literal implements Expression {
constructor(private readonly value: boolean) {}
interpret(): boolean {
return this.value;
}
}
class Variable implements Expression {
constructor(private readonly name: string) {}
interpret(context: Context): boolean {
if (!(this.name in context)) {
throw new ReferenceError(`unknown variable "${this.name}"`);
}
return context[this.name];
}
}
class Not implements Expression {
constructor(private readonly operand: Expression) {}
interpret(context: Context): boolean {
return !this.operand.interpret(context);
}
}
class And implements Expression {
constructor(
private readonly left: Expression,
private readonly right: Expression,
) {}
interpret(context: Context): boolean {
return this.left.interpret(context) && this.right.interpret(context);
}
}
class Or implements Expression {
constructor(
private readonly left: Expression,
private readonly right: Expression,
) {}
interpret(context: Context): boolean {
return this.left.interpret(context) || this.right.interpret(context);
}
}
const rule = new Or(
new Variable("admin"),
new And(new Variable("beta"), new Not(new Variable("banned"))),
);
console.log(rule.interpret({ admin: false, beta: true, banned: false }));
console.log(rule.interpret({ admin: false, beta: true, banned: true }));true
falseEach node does one small thing and delegates to its children, so evaluating the root evaluates the whole tree. The && and || operators short-circuit, so a variable on the right is read only when needed, and an unknown variable that is never reached does not throw. A new operator, such as xor, is a new class that implements Expression.
Building trees by hand is tedious, and a user will not do it. That is the job of the parser.
Tokenizing and parsing
A tokenizer splits the text into words and symbols. A recursive-descent parser then follows the grammar, with one function per rule.
function tokenize(source: string): string[] {
return source.match(/\(|\)|[A-Za-z_][A-Za-z0-9_]*/g) ?? [];
}
class Parser {
private position = 0;
constructor(private readonly tokens: string[]) {}
parse(): Expression {
const expression = this.parseOr();
if (this.position < this.tokens.length) {
throw new SyntaxError(`unexpected "${this.tokens[this.position]}"`);
}
return expression;
}
private peek(): string | undefined {
return this.tokens[this.position];
}
private take(): string {
const token = this.tokens[this.position++];
if (token === undefined) throw new SyntaxError("unexpected end of input");
return token;
}
private parseOr(): Expression {
let left = this.parseAnd();
while (this.peek() === "or") {
this.take();
left = new Or(left, this.parseAnd());
}
return left;
}
private parseAnd(): Expression {
let left = this.parseNot();
while (this.peek() === "and") {
this.take();
left = new And(left, this.parseNot());
}
return left;
}
private parseNot(): Expression {
const token = this.take();
if (token === "not") return new Not(this.parseNot());
if (token === "(") {
const inner = this.parseOr();
if (this.take() !== ")") throw new SyntaxError('expected ")"');
return inner;
}
if (token === "true") return new Literal(true);
if (token === "false") return new Literal(false);
if (token === ")" || token === "and" || token === "or") {
throw new SyntaxError(`unexpected "${token}"`);
}
return new Variable(token);
}
}
function compile(source: string): Expression {
return new Parser(tokenize(source)).parse();
}
const compiled = compile("admin or (beta and not banned)");
console.log(compiled.interpret({ admin: false, beta: true, banned: false }));
console.log(compiled.interpret({ admin: true, beta: false, banned: true }));true
trueEach parser method matches a grammar rule. parseOr reads one or more and terms separated by or, and parseAnd does the same one level down, which is what gives and its higher precedence. parseNot handles the atoms: not, parentheses, literals and variables. The while loops build left-associative trees, so a or b or c becomes (a or b) or c.
The text is compiled once into a tree, and the tree can be evaluated many times with different contexts, so the cost of parsing is paid once per rule, not once per check.
Error handling
A user-facing language needs clear errors. The parser throws SyntaxError with a message, and Variable.interpret throws ReferenceError for unknown names.
for (const source of ["admin and", "(admin or beta", "admin beta", "not"]) {
try {
compile(source);
} catch (e) {
console.log(`${source} -> ${(e as Error).message}`);
}
}
try {
compile("admin and ghost").interpret({ admin: true });
} catch (e) {
console.log((e as Error).message);
}admin and -> unexpected end of input
(admin or beta -> unexpected end of input
admin beta -> unexpected "beta"
not -> unexpected end of input
unknown variable "ghost"The case (admin or beta reaches the end while looking for the closing parenthesis, so take() reports the missing input. For admin beta, the parser finishes after admin and sees a leftover token, which parse() reports. A production language would also track the position of each token to point at the error, and might check variable names at compile time against a list of known facts rather than at evaluation.
Safety
Never use eval or new Function for this job. A rules language that reaches the JavaScript engine lets a user run arbitrary code. The whole value of the pattern here is that the language is small and closed: users can express only what the grammar allows, and the interpreter decides what each construct does.
Bound the input as well. Limit the length of the source and the depth of nesting, since a deeply nested expression can overflow the stack in a recursive parser. A check on the token count before parsing is a cheap guard.
Testing
A table of source strings and expected results gives good coverage with little code.
import { test } from "node:test";
import assert from "node:assert/strict";
const cases: [string, Context, boolean][] = [
["admin", { admin: true }, true],
["not admin", { admin: true }, false],
["a or b and c", { a: true, b: false, c: false }, true],
["(a or b) and c", { a: true, b: false, c: false }, false],
["true and not false", {}, true],
];
for (const [source, context, expected] of cases) {
test(`${source} => ${expected}`, () => {
assert.equal(compile(source).interpret(context), expected);
});
}✔ admin => true
✔ not admin => false
✔ a or b and c => true
✔ (a or b) and c => false
✔ true and not false => trueThe third and fourth cases check precedence and the effect of parentheses, which are where parsers most often go wrong.
When to use it, and when not
Use the Interpreter pattern when the language is small, with a handful of rules, when it changes rarely, and when performance is not critical, since walking a tree of objects is slower than compiled code. It also fits when users genuinely need to write rules without redeploying the program.
Avoid it for large grammars, where the number of node classes and parser functions grows with every rule and becomes hard to maintain. Use a parser generator, a combinator library or an existing expression library instead. For simple needs, a JSON structure describing the condition, such as { "or": [{ "var": "admin" }, ...] }, avoids writing a parser at all, at the cost of being harder for people to type.
Extending the language
A language that works is soon asked to grow. Users want comparisons such as age >= 18, string matching, or a function such as has(role, "editor"). Each extension touches the same four places: the grammar, the tokenizer, the parser and the node classes. Writing the grammar change first, in the same notation as above, keeps the others honest, because the parser functions follow it directly.
Think carefully before each addition, because every construct is something you must keep working. A smaller language is easier to explain to the people who write rules, easier to secure and easier to test. If users ask for loops or assignment, that is a sign that they need a real scripting language, and embedding an existing sandboxed interpreter may serve them better than growing your own.
When you do extend it, keep evaluation free of side effects. A pure expression gives the same result for the same context, which allows you to cache results, to explain why a rule matched and to test it with a table. If a rule must call something with side effects, such as a lookup in a database, pass the data in through the context before evaluation, instead of letting the expression reach out for it.
Finally, consider adding a way to explain a result. An interpreter that returns only false tells the administrator nothing. One that records which sub-expressions were true or false, for example by returning a small trace along with the value, turns a mysterious refusal into a readable reason, which is often the feature that makes users trust a rules engine.


