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

Typescript error 2345 when passing array as variable instead of directly

Question was already asked here but both the solutions provided don’t address nor solve the issue

I was following some TypeScripts examples about generics, in the specific this one.

The example is pretty straightforward:

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

function pickObjectKeys<T, K extends keyof T>(obj: T, keys: K[]) {
  let result = {} as Pick<T, K>
  for (const key of keys) {
    if (key in obj) {
      result[key] = obj[key]
    }
  }
  return result
}

const language = {
  name: "TypeScript",
  age: 8,
  extensions: ['ts', 'tsx']
}

const ageAndExtensions = pickObjectKeys(language, ['age', 'extensions'])

This works. However, if passing the array as a variable, like so:

const keys = ['age', 'extensions']

...

pickObjectKeys(language, keys)

the TypeScript compiler gives error 2345:

Argument of type 'string[]' is not assignable to parameter of type '("age" | "extensions" | "name")[]'.
Type 'string' is not assignable to type '"age" | "extensions" | "name"'.

What’s the catch? How to address this issue?

>Solution :

First, consider making keys readonly:

function pickObjectKeys<T, K extends keyof T>(obj: T, keys: readonly K[]) {

this will allow you to pass readonly arrays now (previously it would’ve errored).

The easiest way to get around this is to use a const assertion:

const keys = ['age', 'extensions'] as const; // readonly ["age", "extensions"]

pickObjectKeys(language, keys); // OK

but you could also cast to ["age", "extensions"] or ("age" | "extensions")[]. However, that does mean you would repeat yourself, so I suggest staying with as const.

Playground

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