Suppose we write a typescript function like so:
function foo(x: number | string): number | string {
switch (typeof x) {
case "string":
// x: string
return x
case "number":
// x: number
return x
}
}
This is great, but you'll notice that the expression
foo(150) has type number | string. By
reasoning outside the type system, we know the result should still be a
number so how do we get our type system to see what we
are. Ideally, we'd want to write something like:
function foo(x: number | string): typeof x {
switch (typeof x) {
case "string":
return x
case "number":
return x
}
}
Unfortunately this doesn't work. When we pass in 150 it
takes on the type of the argument to function
number | string. So, the expression foo(150)
still has type number | string. Well, since that doesn't
help maybe generics can help us.
function foo<T>(x: T): T {
switch (typeof x) {
case "string":
return x
case "number":
return x
}
throw "Type Error!" // !! this is now needed!
}
This does what we want! The expression foo(150) now has
type number (well, in this case 150, so
technically even better). But you'll notice we had to add an exception
for a type error. Meaning now, we can write foo(true) and
our type checker won't catch the error. This is a problem, the point of
typechecker is to catch issues like this. So are we stuck? Well we can
use the concept of 'Fording' which gets its name from the Henry Ford
quote:
Any color the customer wants, so long as it's black.In essence, our generic above already does the first half. It asks for any type
T but how do we make sure it's black (
number | string). Well, we can use the extends
keyword:
function foo<T extends number | string>(x: T): T {
switch (typeof x) {
case "string":
return x
case "number":
return x
}
// no return or throw needed
}
Now, the expression foo(150) has type
number (150). This is because
150: number, thus the type argument
T get's infered to be
number which is an extension of
number | B, meaning the return type of
the function will be number. Importantly, expressions like
foo(true) get correctly identified as not well typed.
Above we saw how we can make a function more generic, by using a type
argument T, and then restrict that type argument to the
specific types we want, T extends number | string, in
order to get more information out of the type system. Yet, this concept
of Fording can be taken further and applied to types themselves.
Suppose we are implementing an interpreter for a statically typed language, to do this we'd represent our program as an Abstract Syntax Tree (AST). We might write some code like this:
type Expr =
| { tag: "num"; val: number }
| { tag: "bool"; val: boolean }
| { tag: "add"; left: Expr; right: Expr } // l + r
| { tag: "eq"; left: Expr; right: Expr } // l == r
This is a great implementation, but notice how we can represent things
like false + true or 5 == false. This may be
fine in a dynamically typed language but in statically typed ones they
are not. So, ideally, we'd want to be able to use typescript to enforce
that our AST is well typed. We can do this by using Fording, but this
time on the type Expr:
type Expr<T extends number | boolean> =
| ( T extends number ? { tag: "num"; val: number } : never )
| ( T extends boolean ? { tag: "bool"; val: boolean } : never )
| ( T extends number
? { tag: "add"; left: Expr<number>, right: Expr<number> }
: never ) // l + r
| ( T extends boolean
? | { tag: "eq"; left: Expr<number>; right: Expr<number> }
| { tag: "eq"; left: Expr<boolean>; right: Expr<boolean> }
: never ) // l == r
In essence, T represents the type of the expression we are
representing. So, if we want to make a number literal or a boolean
literal of type Expr<T>, that T must be
a number or boolean respectively. Likewise,
if we want to make an addition expression, T must be a
number. And because the type variable T
represents the type of the expression, we can use it to enforce that
both sides of our equality operator are the same type.
const x: Expr<number> = { tag: "num", val: 100 }
const y: Expr<number> = { tag: "num", val: 50 }
const z: Expr<boolean> = { tag: "bool", val: true }
const add: Expr<number> = { tag: "add", left: x, right: y }
const eq1: Expr<boolean> = { tag: "eq", left: x, right: y }
const eq2: Expr<boolean> = { tag: "eq", left: z, right: z }
// the following all (correctly) produce type errors in typescript
const a: Expr<boolean> = { tag: "num", val: 100 }
const b: Expr<number> = { tag: "add", left: x, right: z }
const c: Expr<boolean> = { tag: "eq", left: x, right: z }
const d: Expr<number> = { tag: "eq", left: z, right: z }
This, of course, has benefits beyond just allowing the typescript type
system to reject more not well typed code. Suppose we are writing a
function to evaluate our AST. Using the old system we'd write something
like this:
function evaluate(e: Expr): number | boolean {
// implementation left as exercise for the reader :)
}
Our return type must be number | boolean since we don't
know anything about the type of the expression passed in. Yet, with
our new Forded implementation we get to know the type of the resulting
evaluations, and our evaluate function becomes:
function evaluate<T extends number | boolean>(e: Expr<T>): T {
switch (expr.tag) {
case 'num':
return expr.val;
case 'bool':
return expr.val;
case 'add': {
const test = expr
const l = evaluate(expr.left);
const r = evaluate(expr.right);
return l + r;
}
case 'eq': {
const l = evaluate(expr.left);
const r = evaluate(expr.right);
return (l === r);
}
}
}
But wait! If you copy this function you might notice a some type
errors. Specifically, we get type errors when trying to return our
result. When we do the casing on the tags, that should let us know what
the type of T specifically is. In the 'num'
case, we know that T is a number but when we
return typescript forgets this and states that T could be
a boolean. While other languages are designed to deal
with this kind of reasoning, unfortunately we are pushing the bounds of
what typescript was designed to do.
So what can be done? There are three solutions. The first two involve
casting; we can either cast at every return site or we can call a
helper function that evaluates the AST and returns a value of type
number | boolean and cast the result to T.
These are both straightforward solutions but not ideal since if we care
about typescript checking out types for us. So, to avoid casting, we
can make a small change to our Expr<T> type to
include a coercion function:
type Expr<T extends number | boolean> =
| ( T extends number
? { tag: "num"; val: number; coercion: (x: number) => T; }
: never )
| ( T extends boolean
? { tag: "bool"; val: boolean; coercion: (x: boolean) => T; }
: never )
| ( T extends number
? { tag: "add";
left: Expr<number>;
right: Expr<number>;
coercion: (x: number) => T;
}
: never ) // l + r
| ( T extends boolean
? | { tag: "eq";
left: Expr<number>;
right: Expr<number>;
coercion: (x: boolean) => T;
}
| { tag: "eq"; left: Expr<boolean>;
right: Expr<boolean>;
coercion: (x: boolean) => T;
}
: never ) // l == r
// example of how we'd construct a value of this new type
const n: Expr<number> = { tag: "num", val: 100, coercion: x => x }
Now in our evaluate function we can pass the value we
want to return into the coercion function which gives it
the type T which we can then return. The intuition behind
doing this is pretty clever. If we look at the problem we had before in
the 'num' case, the issue was that typescript didn't know
whether T was a boolean or a
number. The coercion function, in effect,
acts as a proof to typescript that T is infact a
number in the 'num' case. Typescript says, "I
don't if T is a number or not," and
coercion responds with, "give me a number and
I will show you that it is a T." All of this allows us to
make not well-typed expression unrepresentable in our AST and allows us
to safely evaluate our AST and know the type of the result, which
allows us to hopefully write safer and more bug free code.
Anyway, your milleage may vary on how practical this actually is, particularly doing it at the type level. I could imagine that someone could apply these concepts to something like handling HTTP responses (or maybe someone has already has) or just any sort of complicated API in general. Of course the main issue is getting people to buy into doing this kind of reasoning but I still think it is pretty cool to see that you can do these kinds of things in typescript, even if the syntax is somewhat verbose. Typescript has lots of interesting tricks that can be done with the type system, so if you write a lot of typescript I encourage you to read more : )