Array Type Guard With A Generic Combinator
A generic combinator lifts an element-level predicate into a whole-array guard, so validate-then-use code narrows unknown[] to T[] after a single check.
Code
// Array-level type guard: every() checks items one by one, then the whole array asserts to string[]
function isString(v: unknown): v is string {
return typeof v === 'string';
}
// Generic combinator: lifts an element-level guard into a list-level guard
function isArrayOf<T>(values: unknown[], guard: (v: unknown) => v is T): values is T[] {
return values.every(guard);
}
const row: unknown[] = ['id-1', 'deploy', 'ok'];
if (isArrayOf(row, isString)) {
const joined: string = row.join('|'); // row is already string[] here
console.log('joined:', joined);
} else {
console.log('row is not all strings');
}
const mixed: unknown[] = ['id-1', 42, 'ok'];
console.log('mixed passes:', isArrayOf(mixed, isString));
// Number columns reuse the same combinator with a separate element guard
function isNumber(v: unknown): v is number {
return typeof v === 'number';
}
const nums: unknown[] = [1, 2.5, 3];
if (isArrayOf(nums, isNumber)) {
const total: number = nums.reduce((sum, n) => sum + n, 0);
console.log('total:', total);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
joined: id-1|deploy|ok
mixed passes: false
total: 6.5How the snippet works
Array Type Guard With A Generic Combinator reduces to the functions isString, isArrayOf and isNumber.
Applying it
The primary signature is function isString(v: unknown)
The demo output is labeled (joined:, mixed passes:, total:), so every line of output points back to the operation that emitted it.
Statements that matter
const total: number = nums.reduce((sum, n) => sum + n, 0);
function isArrayOf<T>(values: unknown[], guard: (v: unknown) => v is T): values is T[] {
return values.every(guard);
}
return typeof v === 'string';
Interactive Tools for This Topic
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `isString`, `isArrayOf`, `isNumber` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.