DEV Community

Cover image for Use opaque types to improve typing on basic types
Sindre Bøyum
Sindre Bøyum

Posted on • Updated on

Use opaque types to improve typing on basic types

Have you ever wanted to give a string field a type alias?

In TypeScript, these are interchangeable:

type Username = string;
type Password = string;
Enter fullscreen mode Exit fullscreen mode

That means that even if we type parameters with A and B:

function logIn(username: Username, password: Password) {}

const username: Username = "username";
const password: Password = "password";

logIn(username, password);
Enter fullscreen mode Exit fullscreen mode

TypeScript won’t stop us from mixing them up:

function logIn(username: Username, password: Password) {}

const username: Username = "username";
const password: Password = "password";

logIn(password, username);
Enter fullscreen mode Exit fullscreen mode

Opaque types is a way to let TypeScript understand what we’re really after, and will make TS shout at us when using the types wrong, just as it would with any other complex type:

type Username = Opaque<string, "Username">;
type Password = Opaque<string, "Password">;

function logIn(username: Username, password: Password) {}

const username: Username = "username";
const password: Password = "password";

logIn(password, username); // 🚨🚨🚨
Enter fullscreen mode Exit fullscreen mode

Read more about them here:
https://codemix.com/opaque-types-in-javascript/

And get the Opaque type from type-fest:
https://github.com/sindresorhus/type-fest/blob/main/source/opaque.d.ts

Photo by Amy Asher on Unsplash

Top comments (0)