Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typesafe new Array().fill() #142

Open
thetarnav opened this issue Apr 24, 2023 · 3 comments
Open

Typesafe new Array().fill() #142

thetarnav opened this issue Apr 24, 2023 · 3 comments

Comments

@thetarnav
Copy link

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
Copy link

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

@qb20nh
Copy link

qb20nh commented Jan 23, 2024

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

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

@ArthurKa
Copy link

ArthurKa commented Jan 23, 2024

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

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

No branches or pull requests

3 participants