NewSortable IDs are here
prefID
Menu

isId() & getPrefix()

Helpers to check whether a value is a given kind of ID, and to read the prefix back out.

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
function isId<P extends string>(
  value: unknown,
  prefix: P,
  separator?: string // default: "_"
): value is `${P}_${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

Custom separators

Both helpers accept an optional separator argument, so they work with generators configured to use something other than the default underscore.