What it is and why to use it
Array.isArray checks whether a runtime value is an array, but does not validate its element types. A second check can verify each element before the program treats the array as a string list. This is useful for processing external lists without trusting a type assertion.
Common mistakes and limitations
A type predicate’s correctness is the author’s responsibility. every skips empty slots in sparse arrays and accepts an empty array; decide whether either case is allowed. A schema with nested objects needs deeper validation than this string-only check.
Run this example
Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.
Terminal — compile and run
npx tsc example.ts --strict --target ES2022 --module commonjs
node example.jsSyntax
Array.isArray(input) && input.every(item => typeof item === "string")Examples
Validating Arrays from unknown
Standalone TypeScript 5.8+ example; expected output is explained below.
function isStringList(input: unknown): input is string[] {
return Array.isArray(input) && input.every((item: unknown) => typeof item === "string");
}
function joinNames(input: unknown): string {
return isStringList(input) ? input.join(", ") : "Invalid list";
}
console.log(joinNames(["John", "James"]));
console.log(joinNames(["John", 42]));- The array test runs first, so every is called only on an actual array.
- Each element must pass the string check before the predicate claims string[].
- The mixed array is rejected and the valid list can be joined safely. For ordinary dense JSON arrays this is a useful boundary check.
- Expected output: John, James Invalid list
Best practices
- A type predicate’s correctness is the author’s responsibility. every skips empty slots in sparse arrays and accepts an empty array; decide whether either case is allowed. A schema with nested objects needs deeper validation than this string-only check.
- Keep external-input validation separate from compile-time type descriptions.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook