Use opaque types to improve typing on basic types
Sindre Bøyum
Posted on May 25, 2022
Have you ever wanted to give a string
field a type alias?
In TypeScript, these are interchangeable:
type Username = string;
type Password = string;
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);
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);
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); // 🚨🚨🚨
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
💖 💪 🙅 🚩
Sindre Bøyum
Posted on May 25, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
undefined Setting Up a Node.js Development Environment with MySQL, Sequelize, and TypeScript
November 29, 2024