User-Defined Type Guards

Write predicate functions that narrow unknown values to concrete types, turning runtime checks into compile-time guarantees at the call site.

TypescriptData Integrity

Code

typescriptsnippet
23 lines
export function isString(value: unknown): value is string {
  return typeof value === "string";
}

export function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

export function isArrayOf<T>(
  value: unknown,
  guard: (item: unknown) => item is T,
): value is T[] {
  return Array.isArray(value) && value.every(guard);
}

export function assertNever(value: never): never {
  throw new Error("unexpected value " + String(value));
}

const input: unknown = JSON.parse("[\"a\", \"b\"]");
if (isArrayOf(input, isString)) {
  console.log(input.map((s) => s.toUpperCase()));
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

[ 'A', 'B' ]

How it works

The working surface is the functions isString, isRecord, isArrayOf and assertNever — everything else is wiring.

There is no validation gate in front of the Error — the throw fires whenever its line runs.

Applying it

The main signature reads export function isString(value: unknown)

isString is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

return typeof value === "object" && value !== null && !Array.isArray(value);
throw new Error("unexpected value " + String(value));
return Array.isArray(value) && value.every(guard);

Interactive Tools for This Topic

FAQ

Is input validated before use?
There is no validation gate: the `Error` raise happens unconditionally whenever its line executes.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `isString`, `isRecord`, `isArrayOf` at load time.