isArray check and inferred type never in TypeScript

Viewed 230

I am trying to do a simple array check in TypeScript, but apparently what it does is infer that if it's not an array (which actually accepts type any as a parameter), then it must be of type never. I got curious about how this works in TypeScript. What is the correct way to handle this inference with isArray specifically?

The code is:

if (Array.isArray(response)) {
    // do something
} else {
    if (response.hasOwnProperty('myProperty')) { // FAILS compilation, because response is of type 'never' here.
        // do something else
    }
}

The same inference actually happens with a check like: if (response instanceof Array)

Is it possible to do this without explicit casting?

1 Answers
Related