It is not allowed to push a number to the array foo in {foo: []}
See original GitHub issueTypeScript Version: Playground
Search Terms: never[]
Code
const foo = { foo: [] };
foo.foo.push(1);
const bar = [];
bar.push(1);
Expected behavior:
TypeScript should infer foo to be of type { foo: any[] }
and therefore foo.foo.push(1);
should be allowed like bar.push(1);
is allowed
Actual behavior: Line 2: Argument of type ‘1’ is not assignable to parameter of type ‘never’.
Playground Link: https://www.typescriptlang.org/play/index.html#src=const foo %3D { foo%3A [] }%3B foo.foo.push(1)%3B const bar %3D []%3B bar.push(1)%3B
Related Issues:
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
Javascript syntax: var array = [].push(foo); - Stack Overflow
Array.prototype.push() always returns the new number of elements in the array. It does not return this instance or a new Array instance.
Read more >Array.prototype.push() - JavaScript - MDN Web Docs
The push() method adds one or more elements to the end of an array and returns the new length of the array. Try...
Read more >array_push - Manual - PHP
I've done a small comparison between array_push() and the $array[] method and the $array[] seems to be a lot faster. <?php $array =...
Read more >Arrays - The Modern JavaScript Tutorial
Arrays. Objects allow you to store keyed collections of values. ... The pop method does not need to move anything, because other elements ......
Read more >Arrays - D Programming Language
A static array with a dimension of 0 is allowed, but no space is allocated for ... error, '$' is not defined, since...
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 tend not to use
const x = [];
. When I do need to initialize a variable to an empty array, I tend to be explicit with the data type.So, I’d use,
const x : /*insert-data-type-here*/[] = []
And
never[]
is assignable to/*insert-data-type-here*/[]
becausenever
is assignable to all types.Seems like @fatcerberus has a link that shows what you are seeing is intended behaviour, though
For
bar
, TS “evolves” the type with each.push()
. So it starts out asany[]
but then evolves tonumber[]
. Push a string afterwards and it may then evolve to(number | string)[]
, etc. I don’t believe that works with[]
in object literals, though–after the initial definition (which is inferred asnever[]
for some reason), the type cannot change further.Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html