N-ate
N-ate

Reputation: 6933

How can I Convert a ReadonlyArray<any> to any[]?

Some native angular functions return a ReadonlyArray. Some native angular callbacks pass ReadonlyArrays. Since my typescript code may be called in many ways, I don't want to require all arrays passed to my functions be ReadonlyArrays.

Hence I need to convert a ReadonlyArray to a javascript native array, [].

Upvotes: 16

Views: 13342

Answers (1)

N-ate
N-ate

Reputation: 6933

The simplest way to convert the ReadonlyArray<any> to any[] is to use one of the available methods of ReadonlyArray.

For this we will use concat(). Calling concat with no parameters on a ReadonlyArray will return an [].

N.B. The same can be achieved with let newArray = [...ReadonlyArray]
(spread operator); it creates a copy of each item.

Note: You can view other ReadonlyArray members here.

Upvotes: 32

Related Questions