ZYinMD
ZYinMD

Reputation: 5069

How to pass "const asserted" variables to functions that accept less strict arguments

playground

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

Answers (2)

HTN
HTN

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

Karol Majewski
Karol Majewski

Reputation: 25790

function fn(arr: readonly string[]) {
    console.log(arr)
}

Upvotes: 1

Related Questions