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
Top comments (0)