ts-reset icon indicating copy to clipboard operation
ts-reset copied to clipboard

Typesafe `new Array().fill()`

Open thetarnav opened this issue 1 year ago • 3 comments

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

thetarnav avatar Apr 24 '23 07:04 thetarnav

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

ArthurKa avatar Aug 19 '23 13:08 ArthurKa

interface Array<T> {
    fill<T2 extends T>(value: T2): Array<T2>;
}

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

qb20nh avatar Jan 23 '24 17:01 qb20nh

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));

ArthurKa avatar Jan 23 '24 17:01 ArthurKa