Skip to content

Instantly share code, notes, and snippets.

@tautologico
Created October 17, 2022 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tautologico/1dc65b28ba374afa3dc6e2b1b10ee1ba to your computer and use it in GitHub Desktop.
Save tautologico/1dc65b28ba374afa3dc6e2b1b10ee1ba to your computer and use it in GitHub Desktop.
Representing discriminated unions/ADTs in TypeScript
// Discriminated Union in TypeScript
interface Integer {
tag: 'integer';
value: number;
}
interface Sum {
tag: 'sum';
op1: Expression;
op2: Expression;
}
type Expression = Integer | Sum;
function createSum(o1: Expression, o2: Expression): Sum {
return { tag: 'sum', op1: o1, op2: o2 };
}
function createInt(n: number): Integer {
return { tag: 'integer', value: n };
}
const e1 = createSum(createInt(3), createInt(5));
function showExpression(e: Expression): string {
switch (e.tag) {
case 'integer':
return `${e.value}`;
case 'sum':
return `(+ ${showExpression(e.op1)} ${showExpression(e.op2)})`;
}
}
function evalExpression(e: Expression): number {
switch (e.tag) {
case 'integer':
return e.value;
case 'sum':
return evalExpression(e.op1) + evalExpression(e.op2);
}
}
console.log(`e1: ${showExpression(e1)} -- value: ${evalExpression(e1)}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment