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 `new Array().fill()` #142

Open thetarnav opened 1 year ago

thetarnav commented 1 year ago

new Array() returns any[], so filling it with given value doesn't narrow the array type. Maybe this could be improved here.

image

https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgJwTAvDMBTA7jAgkuATwAoBGABgEoA6AMwEsAbR4qgWACgB6LmPmAHoB+IA

ArthurKa commented 11 months ago

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

qb20nh commented 6 months ago
interface Array<T> {
    fill<T2 extends T>(value: T2): Array<T2>;
}

Or do specify explicit type new Array<number>(10).fill(0)

ArthurKa commented 6 months ago
interface Array<T> {
    fill<T2 extends T>(value: T2, start?: number, end?: number): Array<T2>;
}
const arr = new Array(10).fill(0, 8);
[...arr].forEach(e => e.toFixed(2));