arraystypescriptsplice

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:

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.