How to do an array check (like Array.isArray()
) with a readonly array (ReadonlyArray
)?
As an example:
it should be like this
interface ArrayConstructor {
isArray(arg: unknown): arg is unknown[] | readonly unknown[];
}
and test it in typescript
const a = ['a', 'b', 'c'];
if (Array.isArray(a)) {
console.log(a); // a is string[]
} else {
console.log(a); // a is never
}
const b: readonly string[] = ['1', '2', '3']
if (Array.isArray(b)) {
console.log(b); // b is readonly string[]
} else {
console.log(b); // b is never
}
function c(val: string | string[]) {
if (Array.isArray(val)) {
console.log(val); // val is string[]
}
else {
console.log(val); // val is string
}
}
function d(val: string | readonly string[]) {
if (Array.isArray(val)) {
console.log(val); // val is readonly string[]
}
else {
console.log(val); // val is string
}
}
function e(val: string | string[] | readonly string[]) {
if (Array.isArray(val)) {
console.log(val); // val is string[] | readonly string[]
}
else {
console.log(val); // val is string
}
}
Here's relevant issue in typescript.
Suggested workaround by @jcalz is adding overload to declaration of isArray
:
declare global {
interface ArrayConstructor {
isArray(arg: ReadonlyArray<any> | any): arg is ReadonlyArray<any>
}
}