ts-reset
ts-reset copied to clipboard
Typesafe `new Array().fill()`
new Array()
returns any[]
, so filling it with given value doesn't narrow the array type.
Maybe this could be improved here.
https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgJwTAvDMBTA7jAgkuATwAoBGABgEoA6AMwEsAbR4qgWACgB6LmPmAHoB+IA
Array.from({ length: 10 }, () => 0)
.
interface Array<T> {
fill<T2 extends T>(value: T2): Array<T2>;
}
Or do specify explicit type new Array<number>(10).fill(0)
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));