Reputation: 5069
const foo = ['a', 'b', 'c', 'd'] as const; // lots of hardcoded strings
let bar: typeof foo[number] = 'b'; // type guard bar - this is why I opt to use "as const" to begin with
function fn(arr: string[]) {
console.log(arr)
}
fn(foo); // error: foo is immutable but arr is mutable
fn(foo as string[]); // also error: you can't convert from immutable to mutable
How can I pass foo
to to fn
as argument? One solution is fn([...foo])
, but I wonder if there's a less hacky way.
Upvotes: 1
Views: 31
Reputation: 3604
The function fn
should accept readonly string[]
as parameter. If you can not make changes to the function, the safest way is fn([...foo])
because you do not want the fn
function to mutate your array. If you are really sure that the function do not modify your array: fn(foo as unknown as string[])
Upvotes: 2