Skip to content

About

Branded types for JavaScript, DOM and Node.js built-in APIs

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

branded-builtins

Nominal types for the built-in APIs you already use.

npm test license

To TypeScript, path.resolve(), Date.now() and performance.now() return a plain string or number, so nothing stops you from mixing them up. This package makes JavaScript, DOM and Node.js built-ins return branded types instead, so those mix-ups become compile errors. It ships no runtime code.

import path from "node:path";
import type { AbsolutePath, EpochMilliseconds } from "@all1ndev/branded-builtins";

function readPost(file: AbsolutePath) {}

readPost(path.resolve("posts/a.md")); // ✅
readPost(path.join(process.cwd(), "posts/a.md")); // ✅ join keeps the brand of an absolute base
readPost("posts/a.md"); // ❌ string is not an AbsolutePath

function isExpired(at: EpochMilliseconds) {}

isExpired(Date.now()); // ✅
isExpired(performance.now()); // ❌ PerformanceTimestamp is a different clock

In the spirit of @total-typescript/ts-reset, and it works alongside it.

Install

npm i -D @all1ndev/branded-builtins

A library whose published declaration files infer branded types imports them from this package, so it needs it in dependencies instead.

Setup

Add one ES entry matching your lib, plus one entry per host, to tsconfig.json:

{
	"compilerOptions": {
		"lib": ["es2024"],
		"types": ["node", "@all1ndev/branded-builtins/es2024", "@all1ndev/branded-builtins/node24"]
	}
}
Entry Use when
/es2024, /es2025, /esnext Your ES lib, see below.
/dom You use lib: ["dom"].
/node22, /node24, /node26 You use that @types/node major.

A Node project that also loads the DOM lib should add /dom too, since performance and crypto then take DOM types. Keep node before the entries, as above: an overload declared later wins, so node after /dom would override its btoa() and atob(). The root entry only exports the brand types and changes nothing on its own.

Pick the ES entry for your lib, or for your target when lib isn't set:

Your lib ES entry
es2024 /es2024
es2025 /es2025
esnext /esnext
Older than es2024 Not supported

Each entry includes the ones below it. Never pick an entry above your lib: it can declare methods your runtime lacks.

Brands

Brands From, for example
📁 Paths and files AbsolutePath, FileDescriptor, FileMode path.resolve(), process.cwd(), fs.openSync()
⏱️ Time EpochMilliseconds, PerformanceTimestamp, Milliseconds, Seconds, Minutes, Hours Date.now(), performance.now(), fs.statSync().mtimeMs
📦 Sizes Bytes, Kilobytes fs.statSync().size, Buffer.byteLength(), process.resourceUsage().maxRSS
🔢 Numbers Finite, Integer, SafeInteger, Uint32, ZeroBased, OneBased Number.isSafeInteger(), array.indexOf(), util.getCallSites()
🔤 Encodings Hex, Base64, Json, EncodedUriComponent, AbsoluteUrl, DataUrl, IsoUtcString, IsoDate, Pem hash.digest("hex"), JSON.stringify(), date.toISOString()
🪪 Identity UUID, Uid, Gid, AsyncId, TimerId crypto.randomUUID(), os.userInfo().uid, window.setTimeout()
🌍 Locales LanguageTag, TimeZoneId, CurrencyCode Intl.getCanonicalLocales(), Temporal.Now.timeZoneId()
🌐 Network IPv4, IPv6, Port, Cidr, MacAddress, HeaderName net.isIPv4(), dns.promises.resolve4(), server.address().port

See API.md for every branded API.

How it works

Each entry adds overloads to the built-in declarations through declaration merging. The added overloads take priority over the originals (see Caveats for one exception), and every original signature stays, so plain arguments still type-check. Brands are erased at compile time.

Caveats

  • New brands can break inference. let p = path.resolve(x); p = "other" stops compiling, because p is now an AbsolutePath.
  • Arithmetic drops brands. performance.now() - start is a plain number.
  • Brands mark the unit, not validity. Date.parse("nope") is still an EpochMilliseconds (NaN).
  • An original overload with a literal parameter wins. TypeScript tries overloads whose parameters are literal types first, in declaration order, so the original dns.promises.resolve(host, "SOA") and tlsSocket.getPeerCertificate() stay plain. Their siblings resolveSoa() and getCertificate() are branded.
  • Values from the host's configuration are only as valid as that configuration. Node doesn't check HOME, TMPDIR or NODE_PATH, so os.homedir(), os.tmpdir() and require.resolve.paths() can be relative when they are. A default resolvedOptions().timeZone or .locale, and Temporal.Now.timeZoneId(), follow TZ and LANG: an unset or invalid TZ gives Etc/Unknown, which Intl and Temporal reject, or undefined.
  • AbsolutePath is absolute in the path flavor that made it. path.win32 on POSIX, or path.posix on Windows, gives paths the host's path.isAbsolute() rejects.
  • Replacing a branded method takes the brand. A stub, override or polyfill must return the branded type, Date.now = () => 1234 as EpochMilliseconds, and so must a mock typed from the method: vi.spyOn(Date, "now").mockReturnValue(0 as EpochMilliseconds).
  • Type predicates narrow through every() and filter(). After ids.every(Number.isInteger), ids is an Integer[] and won't take a plain number. An assertion such as http.validateHeaderName() must be called through a name with an explicit type, as TypeScript requires for every assertion function.
  • Properties can't be branded. Declaration merging can't change a property's type, so process.pid, import.meta.dirname and performance.timeOrigin stay plain. Fields are branded only on objects an API returns.

Compatibility

  • TypeScript 5.9 or later. The /es2025 and /esnext entries need TypeScript 7.
  • @types/node 22.20.0+, 24.19.0+ or 26.6.0+, with the matching entry.
  • Both fs and node:fs style imports, in ES modules and CommonJS.

Versioning

New brands ship in minor releases. Stricter types are the point of this package, so code that relied on a plain type may need an annotation after an upgrade (see Caveats). Renaming or removing an exported brand type is a major release.

Further reading

License

MIT

About

Branded types for JavaScript, DOM and Node.js built-in APIs

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages