Skip to content

About

Nominal Types is a TypeScript library for creating strongly typed values, ensuring type safety and reducing programming errors.

Resources

Contributing

Stars

6 stars

Watchers

1 watching

Forks

Latest commit

 

History

209 Commits

Folders and files

Repository files navigation

@horizon-republic/nominal-types

Code checks npm License Dependencies Node

Runtime-validated nominal types for TypeScript, for the validators and frameworks you already use.

The problem

To TypeScript, an email address and a team ID are both string. Swap them, and the code still compiles:

const sendInvite = (to: string, team: string): void => {
  console.log(`inviting ${to} to team ${team}`);
};

const email = 'jane@example.com';
const teamId = '0190f1c2-3b4a-7c5d-8e9f-0a1b2c3d4e5f';

sendInvite(teamId, email); // compiles, and invites a UUID to a team called jane@example.com

The solution

Give each kind of value its own type. new checks the value, and the compiler keeps the types apart:

import { Email, Uuid } from '@horizon-republic/nominal-types';

const sendInvite = (to: Email, team: Uuid): void => {
  console.log(`inviting ${to} to team ${team}`); // an instance turns into its value in a string
};

const email = new Email('jane@example.com');
const teamId = new Uuid('0190f1c2-3b4a-7c5d-8e9f-0a1b2c3d4e5f');

sendInvite(email, teamId); // inviting jane@example.com to team 0190f1c2-…
sendInvite(teamId, email); // ❌ compile error: Type 'Uuid' is missing the following properties from type 'Email': …
sendInvite('jane@example.com', teamId); // ❌ compile error: Argument of type 'string' is not assignable to parameter of type 'Email'.
new Email('jane@'); // throws NominalError: nominal.Email: must be an email address (was a string of 5 characters)

Every Email you hold is valid, and it has methods such as email.domain. What a nominal type is compares this with Zod's checked strings and with branded strings.

Installation

npm install @horizon-republic/nominal-types

It has no dependencies, and works with both import and require on Node.js 22.12 or later.

Coming from version 2? See How to move from version 2.

Make your own type

A type is a class with a rule. Start from a built-in type, and add getters for its behaviour:

import { AnyString } from '@horizon-republic/nominal-types';

export class Sku extends AnyString.subtype('shop.Sku', /^[A-Z]{3}-\d{4}$/u) {
  public get category(): string {
    return this.value.slice(0, 3);
  }
}

new Sku('ABC-1234').category; // 'ABC'
Sku.parse('abc'); // { ok: false, issues: [{ message: 'must be matched by ^[A-Z]{3}-\d{4}$ (was "abc")' }] }
new Sku('abc'); // throws NominalError: shop.Sku: must be matched by ^[A-Z]{3}-\d{4}$ (was "abc")

Works with your stack

Each adapter is a separate import path. Install the other library only if you use its adapter.

Validators:

Web frameworks:

  • NestJS 11 and 12: NominalPipe from adapters/nest, for parameters, bodies and message payloads. Guide
  • Fastify 5: the fastifyNominal plugin from adapters/fastify, for requests, responses and @fastify/swagger. Guide
  • Hono and Elysia: schemas as they are, with no adapter. Guides for Hono and Elysia
  • Next.js: parse() in server actions and route handlers. Guide

Forms:

API and transport:

  • GraphQL 16 and 17: scalars from toGraphQL() in adapters/graphql. Guide
  • tRPC 11: schemas as input through a two-line helper. Guide
  • superjson: toSuperjson() from adapters/superjson, so instances survive tRPC and Next.js. Guide

Databases (values read back are checked):

API docs:

  • @nestjs/swagger 11 and 12: applyNominalTypes() from adapters/swagger. Guide
  • JSON Schema: built into every type, with no adapter. Guide

Testing:

  • fast-check 4.6 or later: arbitraryOf(), invalidArbitraryOf() and sampleOf() from testing, valid and invalid values for every type and schema. Guide

Every path starts with @horizon-republic/nominal-types/, such as @horizon-republic/nominal-types/adapters/zod.

What else it does

Built-in types

  • Strings: AnyString, NonEmptyString, NonBlankString, Email, E164PhoneNumber, Uuid, UuidV4, UuidV7, Ulid, TypeId, ObjectId, SemVer, Url, HttpUrl, CountryCode, CurrencyCode, DecimalString, LanguageTag, MediaType, HexColor, Base64, Base64Url, Jwt, Hostname, DomainName, IpAddress, Ipv4Address, Ipv6Address, IpPrefix, Ipv4Prefix, Ipv6Prefix, MacAddress, Isbn, Issn, Gtin, Isin, Iban, Bic.
  • Numbers: AnyNumber, FiniteNumber, PositiveNumber, NegativeNumber, NonNegativeNumber, NonPositiveNumber, Float32, Latitude, Longitude, Integer, PositiveInteger, NegativeInteger, NonNegativeInteger, NonPositiveInteger, Int8, Int16, Int32, Uint8, Uint16, Uint32, Port.
  • Big integers: AnyBigInt, PositiveBigInt, NegativeBigInt, NonNegativeBigInt, NonPositiveBigInt, Int64, Uint64.
  • Booleans: AnyBoolean.
  • Money: Money, an amount and a currency.
  • Dates and times, from /temporal: Instant, PlainDate, PlainTime, PlainDateTime, ZonedDateTime, Duration, TimeZoneId.

Built-in types describes each one.

Documentation

  • Tutorial: build a sign-up check, step by step. Start here.
  • Guides: how to do one task.
  • Reference: every export and built-in type.
  • Explanation: why it works the way it does.

Contributing lists the scripts of this repository.

License

Licensed under the terms in LICENSE.

About

Nominal Types is a TypeScript library for creating strongly typed values, ensuring type safety and reducing programming errors.

Resources

Contributing

Stars

6 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages