reactjs - איך לשנות את ערך האובייקט ב-Typescript?
יש לי מערך של אובייקטים, ואני רק מנסה לשנות את ערך האובייקט, אבל אני מקבל את השגיאה "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);
תשובה #1
אתה צריך להפוך את הפונקציה לגנרית על המפתח כי לאינטרפייס שלך יש יותר מסוג אחד של ערך:
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);
תשובה #2
TypeScript מסיק את הסוג מהצהרת המערך הריקה שלך. כדי לתקן זאת, רק צריך להצהיר את המערך שלך כך
const fields: Field[]= [];
הסיבה שאתה מקבל את השגיאה cannot be assigned to never היא כי TypeScript לא יודע אם המפתח שלך הוא required או מפתחות אחרים שהם מסוג string.
כדי לתקן זאת, אתה יכול או להצהיר על סוגים בפרמטרים של הפונקציה שלך כפי שהוזכר על ידי @iz_
function handleChangeField<K extends keyof Field>(
index: number,
key: K,
value: Field[K]
) {
fields[index][key] = value;
}
או שאתה גם יכול לטפל בבדיקת סוג מפורשת בפונקציה שלך -
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);
}
}
