To show the pattern, let's implement a simple interpreter.
Start by defining each union variant, or *kind*, of the type:
```ts
type ExprKind =
| { tag: "Int", value: number }
| { tag: "Add", left: Expr, right: Expr }
```
Then define the type itself as a class:
```ts
class Expr {
constructor(
public line: number,
public kind: ExprKind,
) {}
// ...
}
```
Each instance of `Expr` will have a `line` (source line number), but only *IntExpr* will have `value`, and only *AddExpr* will have `left` and `right`.
To *match* each variant, a type representing an `Expr` with a specific variant:
```ts
type ExprTag = ExprKind["tag"];
type ExprWithKind<TagextendsExprTag> = Expr & { kind: { tag: Tag } };
```
The type `ExprKind["Tag"]` is a union of each `tag` value, i.e. in this example `"Int" | "Add"`. Saying `Tag extends ExprTag` means that `Tag` (type) is either `"Int"` or `"Add"`, i.e. for `.is("Int")`, `Tag` will be `"Int"` and for `.is("Add")`, `Tag` will be `"Add"`. The *narrowed* type `ExprWithKind` is defined by saying that we want an `Expr` that specifically has the `kind.tag` value of `Tag`.
is<TagextendsExprTag>(tag: Tag): this is ExprWithKind<Tag> {
return this.kind.tag === tag;
}
// ...
}
```
The type predicate tells Typescript that it can expect the `Expr` to conform to `ExprWithKind<Tag>` if `.is` evaluates to `true`. Using this, access can be gained to the variant fields in a type safe manner.
throw new Error(`'${expr.kind.tag}' not handled`);
}
// ...
}
```
By having the `tag` invariant, the Typescript compiler can check that you exhaust each variant in a match. To match each variant, I use this pattern ('k-pattern'):
```ts
class Expr {
// ...
eval(): number {
const k = this.kind;
switch (k.tag) { // Typescript language servers can auto-complete all variants