Currently, I'm using Array.apply(null, new Array(10)).map(Number.prototype.valueOf, 0); to create an array of 0.
I'm wondering is there a better (cleaner) way to do this in typescript?
Update! This is now supported out of the box (see TypeScript Playground).
You no longer need to extend the Array interface.
Old answer:
You can add to the open Array<T> interface to make the fill method available. There is a polyfill for Array.prototype.fill on MDN if you want older browser support.
interface Array<T> {
fill(value: T): Array<T>;
}
var arr = Array<number>(10).fill(0);
Eventually the fill method will find its way into the lib.d.ts file and you can delete your one (the compiler will warn you when you need to do this).
As of now you can just do
const a = new Array<number>(1000).fill(0);
Make sure you include <number> otherwise it will infer a's type as any[].
% tsc --version Version 3.9.2 % cat ./fill.ts const a = new Array<number>(1000).fill(0); % tsc ./fill.ts fill.ts:1:35 - error TS2339: Property 'fill' does not exist on type 'number[]'. 1 const a = new Array<number>(1000).fill(0);target setting in tsconfig.json.
Array(10).fill(0).Int32Array(10)if it’s about numbers only.