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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With