Skip to content

Conversation

@genzzo
Copy link

@genzzo genzzo commented Aug 10, 2023

This PR aims to implement the suggestion in #142

It declares the fill method on a readonly array as never (because fill mutates the original array)
It could be improved by removing the method completely from the interface so if someone has any advice on how to do that let me know

It also changes the fill method on the normal array by typing it based on the type of the value provided

Before:

const arr = new Array(10).fill(0) // returns any[]

After:

const arr = new Array(10).fill(0) // returns number[]

This takes into consideration the rest of the arguments of the fill function such that:

  • If the start and end arguments are undefined then the array type is based on the fill value
  • If the start argument is equal to zero and the end argument is undefined, the array is still typed based on the fill value
  • If the start argument is different from zero regardless of the end argument, then the array type is a combination of it's base type and the value type

You can see an example of this in the tests

Note

This type only works if there is a newly created array, it doesn't retype the original array itself
I'm also open to any help or suggestions for this

@ArthurKa
Copy link

Just use Array.from({ length: 10 }, () => 0).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants