typescript - סוג 'string' אינו ניתן להקצה לסוג 'never' ב-obj[key]


עזור לי, בבקשה. אני לא מבין מה לא בסדר. יש לי פונקציה שעורכת טופס. ניסיתי להגדיר את ערך הפרמטר של הפונקציה "editCloneStateForm" מסוג typeof this.form אבל זה גם לא עובד. הקוד שלי:

editCloneStateForm (value: string, key: IServiceDoneItemKeys) {
    if (this.index >= 0) {
      this.cloneStateForm[this.index].cdate = value
    } else {
      this.form[key] = value // Type 'string' is not assignable to type 'never'
    }
  }

form: IServiceDoneItem = {
    id: 0,
    cdate: '',
    counterparty_id: '',
    counterparty_name: '',
    contract_id: '',
    contract_number: '',
    service_id: '',
    statement_id: null,
    service_count: 0,
    cost: 0,
    income: 0,
    agents_commission: 0,
    state_duty: 0,
    ukap: ''
  }
export interface IServiceDoneItem {
  id?: number,
  cdate: string,
  counterparty_id: number | string,
  counterparty_name: string,
  contract_id: number | string,
  contract_number: string,
  service_id: number | string,
  statement_id: number | null,
  service_count: number,
  cost: number,
  income: number,
  agents_commission: number,
  state_duty: number,
  ukap: string
}

export type IServiceDoneItemKeys = keyof IServiceDoneItem

תשובה #1

תשובה מעודכנת

התשובה המקורית הייתה מאפשרת לך להוסיף כל מפתח לאובייקט שלך, מה שיכול להיות משהו שתרצה להימנע ממנו, אולי תרצה רק את זוגות המפתח/ערך הספציפיים האלה.

זה ישמור על הממשק שלך קשוח למפתחות שצוינו:

editCloneStateForm(value: string, key: IServiceDoneItemKeys) {
  if (this.index >= 0) {
    this.cloneStateForm[this.index].cdate = value;
  } else {
    (this.form as Record<IServiceDoneItemKeys, IServiceDoneItem[keyof IServiceDoneItem]>)[key] = value;
  }
}

אבל כנראה כדאי שתבדוק את סוג המפתח שכן הפרמטר value שלך מקבל טיפוס string, אז אנחנו היינו רוצים להקצות רק מפתחות שמאפשרים טיפוסי ערך של string

תשובה מקורית

טייפסקריפט לא יודע מראש באיזה סוג נמצא המפתח שאליו אתה ניגש בממשק שלך ISserviceDoneItem.

אתה יכול ליצור גנרי להרחבה:

export interface Dictionary<T> {
  [key: string]: T;
}

export interface IServiceDoneItem extends Dictionary<string | number | undefined | null> {
  id?: number;
  cdate: string;
  counterparty_id: number | string;
  counterparty_name: string;
  contract_id: number | string;
  contract_number: string;
  service_id: number | string;
  statement_id: number | null;
  service_count: number;
  cost: number;
  income: number;
  agents_commission: number;
  state_duty: number;
  ukap: string;
}

זה יאפשר את סוגי כל המפתחות שלך בממשק שלך.