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

Argument of type 'string' is not assignable to parameter of type '"one" | "two" | "three" | "four" | "five" | "six"'

I have a type:

type OtpCode = {
  one: string;
  two: string;
  three: string;
  four: string;
  five: string;
  six: string;
};

and try to loop this object and set value :

Object.keys(defaultValues).forEach((x, i) => {
      codeValuesForm.setValue(x, 'sometesttext');
    });

x Type is OtpCode, and Typescript tells me that

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

Argument of type 'string' is not assignable to parameter of type '"one" | "two" | "three" | "four" | "five" | "six"'.

How can I solve this to loop this object?

>Solution :

Object.keys() sadly returns string[] and not a union of the keys on the object you pass in. There are many other answers on this which may help you find an appropriate solution, e.g.

Most of the time you can get away with just manually type-casting, e.g.

Object.keys(defaultValues).forEach((key) => { key }); // string
(Object.keys(defaultValues) as (keyof OtpCode)[]).forEach((key) => { key }); // keyof OtpCode

TypeScript 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