total-typescript / ts-reset

A 'CSS reset' for TypeScript, improving types for common JavaScript API's
https://www.totaltypescript.com/ts-reset
MIT License
7.74k stars 117 forks source link

Typesafe array fill #159

Open genzzo opened 11 months ago

genzzo commented 11 months ago

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:

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 commented 11 months ago

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