簡體   English   中英

對象屬性值數組的動態接口

[英]Dynamic interface for array of object property value

我有對象數組。 數組中的每個對象代表一個 html 輸入字段。 我想在字段內的type屬性的基礎上加載不同的接口。

interface Field {
  type: 'text' | 'radio';
  name: string;
}
interface TextField {
  placeholder: string;
}
interface RadioField {
  values: {
    value: string;
    label: string;
  }[];
}
const fields: Field[] = [
  {
    // How to make use of TextField interface here
    type: 'text',
    name: 'firstName',
  }
]

我將建議您通過與擴展FieldCommon接口的TextFieldRadioField的聯合來定義Field類型。 就像你更加精確,使無線電場應該values ,例如:

type Field = TextField | RadioField

interface FieldCommon {
  name: string;
}

interface TextField extends FieldCommon {
  type: 'text'
  placeholder: string;
}

interface RadioField extends FieldCommon {
  type: 'radio'
  values: {
    value: string;
    label: string;
  }[];
}

const fields: Field[] = [
  {
    type: 'text',
    name: 'firstName',
    placeholder:'Test' // valid
  },
  {
    type: 'text',
    name: 'firstName', // error: Property 'placeholder' is missing
  }
]

游樂場鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM