question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Array.isArray type narrows to any[] for ReadonlyArray<T>

See original GitHub issue

TypeScript Version: 2.4.1

Code

declare interface T {
  foo: string;
}

const immutable: T | ReadonlyArray<T> = [];

if (Array.isArray(immutable)) {
  const x = immutable; // Any[]  - Should be ReadonlyArray<T>
} 

const mutable: T | Array<T> = [];

if (Array.isArray(mutable)) {
  const x = mutable; // T[]
} 

Expected behavior: Should type narrow to ReadonlyArray<T>, or at the very least T[].

Actual behavior: Narrows to any[]. Doesn’t trigger warnings in noImplicitAny mode either.

Issue Analytics

  • State:open
  • Created 6 years ago
  • Reactions:132
  • Comments:38 (15 by maintainers)

github_iconTop GitHub Comments

16reactions
RyanCavanaughcommented, Oct 28, 2022

I’ll bring it to the design meeting next week. This is incredibly subtle, unfortunately.

16reactions
RyanCavanaughcommented, Jan 25, 2022

Barring some unforeseen consequence

I have incredibly bad news… 😅. Every time we touch this thing something breaks. Happy to take a PR to try, though.

Read more comments on GitHub >

github_iconTop Results From Across the Web

typescript - Why type inference is lost when using Array.isArray?
As that is the case with ReadonlyArray<T> , control flow analysis now resolves to any[] as the most narrow type possible. Here is...
Read more >
Array.isArray() - JavaScript - MDN Web Docs
isArray () static method determines whether the passed value is an Array. ... It returns true for any value that was created using...
Read more >
Type guards and assertion functions • Tackling TypeScript
isArray ()`, * but also checks if all Array elements are instances of `T`. * As a consequence, the type of `arr` is...
Read more >
Ts-essentials NPM
ts-essentials is a set of high-quality, useful TypeScript types that make ... nested: Readonly<{ a: string; array: ReadonlyArray<Readonly<{ bar: number }>> ...
Read more >
ts-toolbelt/community - Gitter
Wondering about a way to type a “configurable” object containing methods based on an input object. ... Is it just excluding all the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found