Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use toSpliced() without copying the type?

I want to try out the toSpliced() method:

const a = [1, 2] as const 
const b = a.toSpliced(0, 1, 'hi') 

This gives error: Argument of type '"hi"' is not assignable to parameter of type '1 | 2'

I try copy the array:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const copiedA = [...a] //or
const copiedA = a.map(x => x)

or type assert it:

const b = a.toSpliced(0, 1, 'hi') as any

but none of these works. Is there a way to avoid this?

>Solution :

The type of a is readonly [1, 2].

If you want to treat it as something else, you can cast it using as.

const b = (a as readonly any[]).toSpliced(0, 1, 'hi')

or in two lines

const anyArr: readonly any[] = a
const c = anyArr.toSpliced(0, 1, 'hi')

You should replace any with whatever is suitable.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading