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

Advertisements

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

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

Leave a ReplyCancel reply