1.0.1 • Published 10 months ago

opaque-type v1.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
10 months ago

opaque-type

An opaque type helper.

Installation

npm install opaque-type

Usage

import type { Opaque } from "opaque-type";

type AccountId = Opaque<number, "AccountId">;

Why?

Opaque types are a way to ensure you don't mix up different types of values that share the same underlying type, but are fundamentally different.

See the following example, where our account and person identifiers are numbers:

type AccountId = Opaque<number, "AccountId">;
type PersonId = Opaque<number, "PersonId">;

// Image we have a function that gets an account by its account id.
declare function getAccount(id: AccountId);

// And we have account ids and person ids in the same place.
declare const accountId: AccountId;
declare const personId: PersonId;

// TypeScript will complain if we pass an account id when a person id is expected, and viceversa.
getAccount(accountId); // No error
getAccount(personId); // Error

You can also use the { readonly t: unique symbol } object for global uniqueness, but is more verbose.

type AccountId = Opaque<number, { readonly t: unique symbol }>;
type PersonId = Opaque<number, { readonly t: unique symbol }>;
1.0.1

10 months ago

1.0.0

10 months ago