DEV Community

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

Posted on • Edited on

9 4

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more