26

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?

3
  • 3
    In plain JS you can do something like Array(10).fill(0). Commented Apr 22, 2015 at 1:03
  • Or one of the typed arrays, e. g. Int32Array(10) if it’s about numbers only. Commented Apr 22, 2015 at 1:04
  • @Xufox *With a polyfill, but definitely the best way to go. Commented Apr 22, 2015 at 1:19

4 Answers 4

26

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

View on Playground

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

Sign up to request clarification or add additional context in comments.

Comments

14

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[].

4 Comments

This is driving me crazy. It fails in the latest typescript compiler.% 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);
You probably need to change the target setting in tsconfig.json.
That's right. Array.fill is ES6, so target must specify ES6. Thank you for the tip!
I don't like this approach, because Array<number>(1000) is invalid assumption and it's easy to cause a bug if you change the fill, for example, or split creation and filling to separate variables.
5

You could pass an integer argument to the Array constructor, this will return a new JavaScript array with its length property set to that number, plus you can use .fill to fill all the elements of an array from index zero.

const data = Array(10).fill(0)
console.log(data)

Comments

4

Having reviewed the concept of array holes I would do:

Array.apply(null, new Array(10)).map(()=> 0);

Not a big saving but is some.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.