Nikolay Khvan
Nikolay Khvan

Reputation: 123

How to change the object value in typescript?

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);

Upvotes: 3

Views: 1562

Answers (2)

warl0ck
warl0ck

Reputation: 3464

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);
      }
  }

Upvotes: 2

iz_
iz_

Reputation: 16633

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);

Upvotes: 2

Related Questions