TL;DR · UUIDs → TNIDs · TypeScript

Same job. More useful IDs.

Know what an ID refers to. Catch mix-ups. Keep your UUID column.

01 / Recognize

Which record does this audit entry refer to?

An audit log can reference users, posts and other records through the same targetId field.

UUID

const userId = crypto.randomUUID();
const postId = crypto.randomUUID();

console.log({ targetId: userId });
console.log({ targetId: postId });

Audit log · example output

{ targetId: "8c0fdc62-d785-4dfa-82d2-75c88002d026" }
{ targetId: "b07a4d61-bcd5-43bb-942e-b31fb20ea2cc" }

The targetId alone doesn’t tell you whether to look for a user or a post.

TNID

import { Tnid, type TnidType } from "@tnid/core";

const UserId = Tnid("user");
type UserId = TnidType<typeof UserId>;

const PostId = Tnid("post");
type PostId = TnidType<typeof PostId>;

const userId = UserId.new_v0();
const postId = PostId.new_v0();

console.log({ targetId: userId });
console.log({ targetId: postId });

Audit log · example output

{ targetId: "user.Br2flcNDfF6LYICnT" }
{ targetId: "post.C2_xX1wLN9fRh5B77" }

Same targetId field. The ID itself tells you what kind of record it refers to.

Generated values vary. The examples below continue with these IDs.

02 / Compare

Equality. Lookups. Sorting. All by value.

TNIDs and UUIDs are 128-bit values. TNID strings have one exact spelling and preserve value order. Here’s what that buys you.

UUID: one ID, two string keys

// Same user, different API casing conventions:
const usersApiId: string = "d6157337-0ebc-8686-83ab-4075a34cdcde";
const auditApiId: string = "D6157337-0EBC-8686-83AB-4075A34CDCDE";
const cache = new Map([[usersApiId, "Alice"]]);

console.log({ equal: usersApiId === auditApiId });
console.log({ uniqueIds: new Set([usersApiId, auditApiId]).size });
console.log({ cachedUser: cache.get(auditApiId) });

Console

{ equal: false }
{ uniqueIds: 2 }
{ cachedUser: undefined }

Same 128 bits. Unequal strings, duplicate IDs in a set, and a cache miss.

TNID: one ID, one string key

// The same user ID from those two APIs:
const a = UserId.parse(usersApiId);
const b = UserId.parse(auditApiId);
const cache = new Map([[a, "Alice"]]);

console.log({ equal: a === b });
console.log({ uniqueIds: new Set([a, b]).size });
console.log({ cachedUser: cache.get(b) });

Console

{ equal: true }
{ uniqueIds: 1 }
{ cachedUser: "Alice" }

Same value, same string: equality, deduplication and lookup all agree.

UUID strings: wrong order

// Users API (lowercase):
const earlier = "d6157337-0ebc-8686-83ab-4075a34cdcde";
// Audit API (uppercase):
const later = "D6157343-97D8-882F-8598-2AB72D18C208";

console.log({ inOrder: earlier < later });

const [first, second] = [later, earlier].sort();
console.log({ first });
console.log({ second });

Console

{ inOrder: false }
{ first: "D6157343-97D8-882F-8598-2AB72D18C208" }
{ second: "d6157337-0ebc-8686-83ab-4075a34cdcde" }

Mixed case is valid UUID hex. Normalize it before equality checks or sorting.

TNID strings: correct order

// TNIDv0 strings from different milliseconds:
const earlier = "user.Br2flcNDfF6LYICnT";
const later = "user.C2_xX1wLN9fRh5B77";

console.log({ inOrder: earlier < later });

const [first, second] = [later, earlier].sort();
console.log({ first });
console.log({ second });

Console

{ inOrder: true }
{ first: "user.Br2flcNDfF6LYICnT" }
{ second: "user.C2_xX1wLN9fRh5B77" }

String order matches value order. No normalization or custom comparator needed.

Names sort first. Within one name, TNIDv0 sorts by creation millisecond; same-millisecond IDs are unordered. Use case-sensitive, non-locale comparison, as with < and default .sort() above—not localeCompare().

03 / Catch mistakes

A post ID shouldn’t work as a user ID.

With plain strings

function userUrl(id: string) {
  return `/users/${id}`;
}

console.log({ url: userUrl(postId) });

Console

{ url: "/users/post.C2_xX1wLN9fRh5B77" }

Valid string. Wrong URL. TypeScript accepts it.

Expect a UserId, not just any string

function userUrl(id: UserId) {
  return `/users/${id}`;
}

userUrl(userId); // OK
userUrl(postId); // Type error

TypeScript · before your code runs

Argument of type 'TnidValue<"post">' is not
assignable to parameter of type 'TnidValue<"user">'.

This is a compile error, not a failed database lookup.

Incoming request? Parse the string.

// e.g. the id from /users/:id
const param = "user.Br2flcNDfF6LYICnT";
const id = UserId.parse(param);

console.log({ url: userUrl(id) });

Console

{ url: "/users/user.Br2flcNDfF6LYICnT" }

Use the parsed ID in your typed functions.

Wrong kind? Reject it at the boundary.

try {
  UserId.parse("post.C2_xX1wLN9fRh5B77");
} catch (error) {
  const message = (error as Error).message;
  console.log({ message });
}

Console

{ message: 'TNID name mismatch: expected "user", got "post"' }

Your request handler can catch this and return 400.

04 / Store

Same UUID column. Same queries.

PostgreSQL example: keep your UUID column, primary key and index. No ALTER TABLE.

Your existing table · unchanged

CREATE TABLE users (
  id uuid PRIMARY KEY
);

db is your existing, connected PostgreSQL client (pg).

INSERT a TNID into that UUID column

const inserted = await db.query(
  "INSERT INTO users (id) VALUES ($1) RETURNING id",
  [UserId.toUuidString(userId)],
);

console.log({ stored: inserted.rows[0].id });

Console

{ stored: "d6157337-0ebc-8686-83ab-4075a34cdcde" }

RETURNING shows the value PostgreSQL stored: a native, 16-byte UUID.

SELECT it back as a TNID

const result = await db.query(
  "SELECT id FROM users WHERE id = $1",
  [UserId.toUuidString(userId)],
);
const loaded = UserId.parse(result.rows[0].id);

console.log({ loaded });
console.log({ sameId: loaded === userId });

Console

{ loaded: "user.Br2flcNDfF6LYICnT" }
{ sameId: true }

The name survived UUID storage. No type column or prefix to reattach.

Generate the TNID in your app instead of a database UUID default. UUID validators must accept version 8.

05 / Choose

Random, or time-sortable?

Want creation-time ordering?

UserId.new_v0()

Like UUIDv7: timestamp + randomness. Sorts by millisecond within a name; also reveals that time. IDs made in the same millisecond are unordered.

Want no timestamp in the ID?

UserId.new_v1()

Like UUIDv4: random. Same names, types and UUID storage; no creation-time ordering.

Before you switch

What about my existing UUIDs?

Prefer one format per entity type. Existing UUIDv4/v7 values cannot become TNIDs without changing the ID.

Keep an existing type on UUIDs and use TNIDs for a new type, or plan a migration of a type’s IDs and their references.

Mixing UUIDs and TNIDs for the same type is possible, but it weakens the contract: your code must handle both instead of relying on every ID carrying a name. Treat that as a migration compromise, not the destination. Migration considerations.

Why not add a prefix and a TypeScript brand to my UUIDs?

You can. TNID packages those conveniences into a format whose name survives UUID storage and can be checked at runtime. An added user_ prefix lives outside the UUID; a TypeScript-only brand disappears at runtime. Compare formats.

What’s the trade-off?
  • Short, permanent names: 1–4 characters, a–z and 0–4. Changing the name changes the ID.
  • Fewer random bits: TNIDv1 has 100 versus UUIDv4’s 122; TNIDv0 has 57 random bits per millisecond. A billion TNIDv1s under one name have about a 1 in 2.5 trillion collision chance. Keep your unique constraint. High-volume considerations.
  • Case-sensitive strings: preserve case in URLs and JSON. Use UUID storage, or a binary collation for text columns.