3

I have an array of objects, and I am just trying to change the object value, but I am getting the error "Type 'string | boolean' is not assignable to type 'never'. Type 'string' is not assignable to type 'never'".

 interface Field {
 _id: string;
 name: string;
 title: string;
 required: boolean;
 }

 const fields: Field[] = [{ _id: "", name: "", title: "", required: 
 false }];

 function handleChangeField(
    index: number,
    key: string,
    value: string | boolean
  ) {
    fields[index][key as keyof Field] = value; //Error
  }


 handleChangeField(0, "required", true);

2 Answers 2

2

You need to make the function generic on the key because your interface has more than one type of value:

interface Field {
    _id: string;
    name: string;
    title: string;
    required: boolean;
}

const fields: Field[] = [{ _id: "", name: "", title: "", required: false }];

function handleChangeField<K extends keyof Field>(
    index: number,
    key: K,
    value: Field[K]
) {
    fields[index][key] = value;
}


handleChangeField(0, "required", true);
Sign up to request clarification or add additional context in comments.

Comments

2

Typescript is inferring type from your array decleration of empty array. To fix this you just need to declerare your array like

const fields: Field[]= [];

Reason you are getting error cannot be assigned to never is because typescript doesnt know if you key is required or other keys which are of type string.

To fix that you can either declerare types in your function parameters as mentioned by @iz_

function handleChangeField<K extends keyof Field>(
    index: number,
    key: K,
    value: Field[K]
) {
    fields[index][key] = value;
}

or you could also handle explicit type check in your function -

 function handleChangeField(
    index: number,
    key: keyof Field,
    value: string | boolean
  ) {
      if (key === "required") {
          fields[index][key] = (value as boolean);
      } else {
          fields[index][key] = (value as string);
      }
  }

1 Comment

I just forget to put it in my example, but I have it in my source code, and it still does not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.