I encounter this issue repeatedly (playground link):
const arr = [1,2,3] as const
const doSomethingWithNumbers = <T extends number[]>(numbers: T) => {}
doSomethingWithNumbers(arr)
// ^
// Argument of type 'readonly [1, 2, 3]' is not assignable to parameter of type 'number[]'.
// The type 'readonly [1, 2, 3]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.
I understand that I can adjust the function to also accommodate readonly
arrays:
export type AllowReadonly<T extends any[]> = T | readonly T[number][]
const doSomethingWithNumbers = <T extends <number[]>>(numbers: AllowReadonly<T>) => {}
However, this leads to the same issue within doSomethingWithNumbers
, as the numbers
parameter can now also be readonly
.
What is a effective way to address this challenge?