Here is the most concise solution so far:
function isArrayOfStrings(value: unknown): value is string[] {
return Array.isArray(value) && value.every(item => typeof item === "string");
}
Note that value.every
returns true
for an empty array. To return false
for an empty array, add value.length > 0
to the condition clause:
function isNonEmptyArrayOfStrings(value: unknown): value is string[] {
return Array.isArray(value) && value.length > 0 && value.every(item => typeof item === "string");
}
There is no any run-time type information in TypeScript (and there won't be, see TypeScript Design Goals > Non goals, 5), so there is no way to get the "type" of elements of an empty array. For non-empty array all you can do is to check the type of its items, one by one.
Type predicate value is string[]
narrows type of value
to string[]
in the corresponding scope. This is a TypeScript feature, the real return type of the function is boolean
.