Created
October 17, 2022 00:23
-
-
Save tautologico/1dc65b28ba374afa3dc6e2b1b10ee1ba to your computer and use it in GitHub Desktop.
Representing discriminated unions/ADTs in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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