NewSortable IDs are here
prefID
Menu

isId(), getPrefix() & parseId()

Helpers to check whether a value is a given kind of ID, read the prefix, or parse both components.

isId()

A type guard that returns true when a value is a string beginning with ${prefix}${separator}. On the true branch, TypeScript narrows the value to the matching prefixed-ID type.

ts
// Default separator — narrows to `${P}_${string}`:
function isId<P extends string>(
  value: unknown,
  prefix: P,
): value is `${P}_${string}`;

// Custom separator — narrows to `${P}${S}${string}`:
function isId<P extends string, S extends string>(
  value: unknown,
  prefix: P,
  separator: S,
): value is `${P}${S}${string}`;
import { isId } from "prefid";

function handle(value: unknown) {
  if (isId(value, "user")) {
    // value is now typed as `user_${string}`
    value.toUpperCase();
  }
}

isId("user_abc", "user");  // => true
isId("order_abc", "user"); // => false
isId(42, "user");          // => false
const { isId } = require("prefid");

function handle(value) {
  if (isId(value, "user")) {
    // value is a "user_…" string here
    value.toUpperCase();
  }
}

isId("user_abc", "user");  // => true
isId("order_abc", "user"); // => false
isId(42, "user");          // => false

getPrefix()

Extracts the prefix portion of an ID, or returns undefined when the separator is absent (or leading).

ts
function getPrefix(
  value: string,
  separator?: string // default: "_"
): string | undefined
import { getPrefix } from "prefid";

getPrefix("user_a1b2c3");  // => "user"
getPrefix("order_9f8e7d"); // => "order"
getPrefix("no-separator"); // => undefined
const { getPrefix } = require("prefid");

getPrefix("user_a1b2c3");  // => "user"
getPrefix("order_9f8e7d"); // => "order"
getPrefix("no-separator"); // => undefined

parseId()

parseId decomposes a generated ID back into its prefix and body. It returns undefined when the value is not a string, has no separator, or has an empty body. Like isId, it does not validate the body's contents — a value such as "user_@@@" still parses.

import { parseId } from "prefid";

const myId = "user_wLCFZ7EEjBYFmsbnthUkGspX";
const parsed = parseId(myId);

if (parsed) {
  console.log(parsed.prefix); // "user"
  console.log(parsed.id);     // "wLCFZ7EEjBYFmsbnthUkGspX"
}

// Fails safely on invalid inputs
console.log(parseId("nosep")); // undefined
console.log(parseId("user_")); // undefined
const { parseId } = require("prefid");

const myId = "evt_00VUDe8n8qKHoKl0tXbtTK56E";
const parsed = parseId(myId);

console.log(parsed?.prefix); // "evt"
console.log(parsed?.id);     // "00VUDe8n8qKHoKl0tXbtTK56E"

Custom separators

All three helpers accept an optional separator argument, so they work with generators configured to use something other than the default underscore. When you pass one to isId, the separator flows into the type it narrows to — so isId(value, "user", "-") narrows to `user-${string}`, not the underscore form.