Array.isArray type narrows to any[] for ReadonlyArray<T>
See original GitHub issueTypeScript 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:
- Created 6 years ago
- Reactions:132
- Comments:38 (15 by maintainers)
Top 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 >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I’ll bring it to the design meeting next week. This is incredibly subtle, unfortunately.
I have incredibly bad news… 😅. Every time we touch this thing something breaks. Happy to take a PR to try, though.