Opaque TypeScript
Published: 2024-03-02 21:50:10

---
title: Opaque TypeScript
published: true
---
Let us begin straight with [the example](https://www.typescriptlang.org/play?target=99#code/PTAEGMFMBsGcEsCusB0AXWAoAdgQwLaSwAOuUoAwqAN6aj2gAmk40uATpBAPbaxqgA+gC5QibPACOiLrACe+AEbdoAbkx0GkAB7Fu7AWjnEuFGAmSgAvKGyIlkdqABkNUAG1BAXVFGT3ADMhUABfDQZQHT0DUADxcDR4XlB8XABrSAAKO3xRHMVHAEpRMzgkWBpNCPpONER2bFt7UFwK0otYdQiwqsjdfQE47ASkxtxGRkyoaBLzcoAaFonIbEZZsuRiyjnLWmqGWvrG6dAAaiXmVZa2nc7esJ6QWNwAC05sF8h4NHQsPEISGQuAAxSoRZisDhccC8fhCUTiKQyUDyJQqdS9KIDUB+EGvd6fb7WJoOJyuageby+YyQQLBHoRLExIYjZKpDLZex5ewFdhbYH4laEgR7fagQ4NEnXUACt5Cr5oLoMBlafrM+KJZLjSYBV6iWUEhWLbUrNYywUfBX8i3CsFiiWNXUvM4XU3Sg3y75K+gPDRPeCrHS-TAwviDG0K4nAlDsrIABkK6lDcOmHWJFBj6XjiY0yZUkBQ0G4AHNMk7Dd9FqnyonQE8i8XYKIAERxxZx5uYaPassRyvPOWW7457sTKa3Rblz1oHMZnvV5CTvsz9RzscL2BV245oA) after which we will discuss the what, why and how.

You don't need to understand everything in the code.
But note that we have two values: `fahrenheit` and `celsius`.
Both of them have the `Fahrenheit` and `Celsius` types respectively.
But even though TypeScript is a structural language and both of the types are essentially numbers, **they are not interchangeable**. On top of that we can't even write `F.add(fahrenheit, celsius as F.Fahrenheit);`.
✨ Pure miracle ✨

## The what
> An opaque data type is a data type whose concrete data structure is not defined in an interface. This enforces information hiding since its values can only be manipulated by calling subroutines that have access to the missing information.
>
> [Wikipedia](https://en.wikipedia.org/wiki/Opaque_data_type#:~:text=In%20computer%20science%2C%20an%20opaque,access%20to%20the%20missing%20information.)

Translating it from the Wikipedian, the opaque type is an encapsulation (hiding internal structure) that is not limited to OOP (classes).

The idiomatic alternative using classes would look [like this](https://www.typescriptlang.org/play?#code/MYGwhgzhAEDCCmIIEsCuMDeAoavoGIA3MEVeALmgDtUBbAI3gCcBuHPYAeyogBcnUwXpyYAKYqQrU6jJgEpo2PMui8AFsggA6IiTLQAvNAlk2ygL5Z2uAObxexvfFFzKNBs0XWVTe6iZUqhraupJmeJbeEPaOkuJObjLMCkoquOqaOibwhrGm3pHKAA6o9CDIwNBgACbVojXV8FTVlAhIaBAp3soZIdm5vVlO0ADUVbVN1UNhBViRoJAwAGJgar5UavDIDqm4oWSJHqzeXDz8gsJi2YeyXWnpwdP6RtnhuIV4dg7ZLjeeuz4-AEgpl9vA3tAPrhot8nPFJH95F57iC+sMXk4IVDoCUyhVxnUGpNKCs1k1Nts7vdBmCBo9aWMic0nuDZpEAPTs6DIZrwAAeWl4ECwpz40AAZqt1hSHEYqPAAO7QUnSra8UQABjkbFFDmAiBQ6Fy8qVbUNEE12qsos4IHgWhAnBsoklZI2aq02QANNB9e10J6nNroJzoI6bBBKAAiDU+jVRrCu1XbLQNF1S8lqq1JzMptN+81WgsdVO1dNumVFg0l-PV9DaoA)
This version is more readable and less cryptic, but we are not always able/want to use classes.

## Thy why
A typical example of a classless circumstance could be a Flux architecture (like Redux), where behavior is separated from data.
But there are some other a bit less obvious reasons to give the opaque type a try:

### True guard
Imagine that we need to model a domino type.
Usually, we go ahead and do something like:
```typescript
type Domino = [DominoValue, DominoValue];
type DominoValue = 1 | 2 | 3 | 4 | 5 | 6;
```
This is a good example of using TypeScript types, but **it does not always make sense or save us from a wrong structure.**
Because such type is safe as long as **we** are responsible for making the instances.
As an example, take a look at the following express router:
```typescript
	Router()
		.post<unknown, unknown, Domino>("/add", (req, res) => ...)
```
We promise to the compiler that the `req.body` has the `Domino` type, while it can be wrong.
Typically to guard the type we make some validation function, like `function isValid(domino: Domino): boolean { ... }`, but we can forget to call the guard and all typing is just a nice description, not an actual validation.
Opaque type can help us to apply the type-level programming, where the result of a validation is another type.

So that the only way to create the domino type is a specific validation function so that the request body is just a raw input
```typescript
// domino.ts
declare const domino: unique symbol;
export type Domino = [number, number] & { [domino]: "Domino" };

export function createDomino(rawData: [number, number]): Domino | false {
	for (const value of rawData) {
        if (value < 1 || value > 6) {
            return false;
        }
    }
    return rawData as Domino;
}

console.log(createDomino([1, 2]))  // [1, 2]
console.log(createDomino([-1, 2])) // false
console.log(createDomino([5, 29])) // false
```

### Phantom type
Phantom type is a way to differentiate types using unused generic parameters.
The most typical example is making an `Id` type that is attached to a specific entity so that it can not be mixed up with another type's id.
Here is [the example](https://www.typescriptlang.org/play?#code/HYQwtgpgzgDiDGEAEBJAIkg3gKCXpAJhPADYgBOy8A9sFAC5ICWBAXEgK7BMCOHyUAJ5gARtRIBubLnwQAHjGrlG9QTGQoCAHgBCAPiQBeJA3JNgAcyQAyLEkogCtEoKQBtFgF12OpAF8pGTx5RWUkADMueHomWiQwEABrCE1dPQAKAEp2VP0sIPw8SnoOcmAkAFkQegALADpyEGAnMCy6+moAZXozSyykEChUbX0pQr9sCexzeghycIRkAAVqBnzClhy0OtSVhj0x-DECQXZTcwtDvA4oOa2d7QBVW-IDyekZuYXEJGe59fwm1Q21Sf1eVyQoEgZx6FykU0iwGisXKJGoFj29AAgs0wZooOlFAx2JiADScF7sMGZAF4AD0dKQAGFqGAYEwSMgYpAkHNyEpySJiIN+EgifQAORDJoEClzKXMAjSygmADuIHUBAKNDojBYUHYbnQDy0mL05ONoJeek8RncNzmdRY5PFToInghOqg4ggdTRFnS+sy8Ok2CAA).
Note that even though both of the ids are strings, **we can not use the post's id in place of the user's id** and vice versa.

## The how
As you may have noticed, the key part is the `unique symbol`.
We declare a file local symbol, that serves as a specific key in an object.

Technically it is not a pure opaque type, because we still se the actual internal structure from outside.
Still, since symbols are unique, only the local symbol can be used while creating opaque types instance.

Even though we never actually initialise the symbol, we can do that, but in this case, we affect the resulting JS object's structure, which is not always desirable.