Please do not link to this article on Reddit or Hacker News.

Refinements are a frequently used aspect of any type system. They are so ingrained in the way that we program and even the way that we think you might not even notice them.

In the code below, value can either be “A” or “B” and an if statement

function method(value: "A" | "B") {

if (value === "A") {

// value is "A"

}

}

Inside of the if block we know that value must be “A” because that’s the only time the if-statement will be truthy.

The ability for a static type checker to be able to tell that the value inside the if statement must be “A” is known as a refinement.

Next we’ll add an else block to our if statement.

function method(value: "A" | "B") {

if (value === "A") {

// value is "A"

} else {

// value is "B"

}

}

Inside of the else block we know that value must be “B” because it can only be “A” or “B” and we’ve removed “A” from the possibilities.

Refinements also includes the ability for a static type checker to be able to eliminate options from a group as they are refined away.