How to check if an object is a readonly array in TypeScript?

mam*_*miu 2 arrays typechecking typescript

How to do an array check (like Array.isArray()) with a readonly array (ReadonlyArray)?

As an example:

type ReadonlyArrayTest = ReadonlyArray<string> | string | undefined;

let readonlyArrayTest: ReadonlyArrayTest;

if (readonlyArrayTest && !Array.isArray(readonlyArrayTest)) {
  // Here I expect `readonlyArrayTest` to be a string
  // but the TypeScript compiler thinks it's following:
  // let readonlyArrayTest: string | readonly string[]
}
Run Code Online (Sandbox Code Playgroud)

With an usual array the TypeScript compiler correctly recognises that it must be a string inside the if condition.

Ale*_* L. 6

这是打字稿中相关问题。

@jcalz建议的解决方法是在声明中增加重载isArray

declare global {
    interface ArrayConstructor {
        isArray(arg: ReadonlyArray<any> | any): arg is ReadonlyArray<any>
    }
}
Run Code Online (Sandbox Code Playgroud)