Runtime-validated nominal types for TypeScript, for the validators and frameworks you already use.
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.comGive 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.
npm install @horizon-republic/nominal-typesIt 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.
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")Each adapter is a separate import path. Install the other library only if you use its adapter.
Validators:
- ArkType 2.2 or later:
toArk()andfromArk()fromadapters/arktype. Guide - Zod 4:
toZod()fromadapters/zod. Guide - Valibot 1:
toValibot()fromadapters/valibot. Guide - class-validator 0.14 and 0.15:
@NominalField()fromadapters/class-validator. Guide - any Standard Schema library: the type itself, or
n.of(Type), with no adapter. Guide
Web frameworks:
- NestJS 11 and 12:
NominalPipefromadapters/nest, for parameters, bodies and message payloads. Guide - Fastify 5: the
fastifyNominalplugin fromadapters/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:
- React Hook Form 7: its Standard Schema resolver hands over instances. Guide
- TanStack Form 1: a small function per field. Guide
API and transport:
- GraphQL 16 and 17: scalars from
toGraphQL()inadapters/graphql. Guide - tRPC 11: schemas as input through a two-line helper. Guide
- superjson:
toSuperjson()fromadapters/superjson, so instances survive tRPC and Next.js. Guide
Databases (values read back are checked):
- MikroORM 7:
toMikroOrm()fromadapters/mikro-orm. Guide - TypeORM 0.3.13 or later, and 1:
toTypeOrm()fromadapters/typeorm. Guide - Drizzle:
toDrizzle()fromadapters/drizzle. Guide - Sequelize 6:
toSequelize()fromadapters/sequelize. Guide
API docs:
- @nestjs/swagger 11 and 12:
applyNominalTypes()fromadapters/swagger. Guide - JSON Schema: built into every type, with no adapter. Guide
Testing:
- fast-check 4.6 or later:
arbitraryOf(),invalidArbitraryOf()andsampleOf()fromtesting, 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.
- Check a whole request body with
n.object(), with no other library. - Check one field against another with
n.constraint(). - Report problems by row and column, such as a SKU repeated in an import, with
n.rule(). - Make a value object of several fields, with getters and
copyWith(). - Read configuration from environment variables with
fromEnv(). - Keep values out of error messages, such as passwords.
- 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.
- 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.
Licensed under the terms in LICENSE.