Nominal types for the built-in APIs you already use.
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 clockIn the spirit of @total-typescript/ts-reset, and it works alongside it.
npm i -D @all1ndev/branded-builtinsA library whose published declaration files infer branded types imports them from this package, so it needs it in dependencies instead.
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 | 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.
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.
- New brands can break inference.
let p = path.resolve(x); p = "other"stops compiling, becausepis now anAbsolutePath. - Arithmetic drops brands.
performance.now() - startis a plainnumber. - Brands mark the unit, not validity.
Date.parse("nope")is still anEpochMilliseconds(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")andtlsSocket.getPeerCertificate()stay plain. Their siblingsresolveSoa()andgetCertificate()are branded. - Values from the host's configuration are only as valid as that configuration. Node doesn't check
HOME,TMPDIRorNODE_PATH, soos.homedir(),os.tmpdir()andrequire.resolve.paths()can be relative when they are. A defaultresolvedOptions().timeZoneor.locale, andTemporal.Now.timeZoneId(), followTZandLANG: an unset or invalidTZgivesEtc/Unknown, whichIntland Temporal reject, orundefined. AbsolutePathis absolute in the path flavor that made it.path.win32on POSIX, orpath.posixon Windows, gives paths the host'spath.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()andfilter(). Afterids.every(Number.isInteger),idsis anInteger[]and won't take a plain number. An assertion such ashttp.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.dirnameandperformance.timeOriginstay plain. Fields are branded only on objects an API returns.
- TypeScript 5.9 or later. The
/es2025and/esnextentries need TypeScript 7. @types/node22.20.0+, 24.19.0+ or 26.6.0+, with the matching entry.- Both
fsandnode:fsstyle imports, in ES modules and CommonJS.
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.