简体   繁体   English

对象属性值数组的动态接口

[英]Dynamic interface for array of object property value

I have array of objects.我有对象数组。 Each object inside array represents an html input field.数组中的每个对象代表一个 html 输入字段。 I want to load different interface on the base of type property inside the field.我想在字段内的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',
  }
]

I will recommand you to define the Field type by the union with TextField and RadioField that extends a FieldCommon interface.我将建议您通过与扩展FieldCommon接口的TextFieldRadioField的联合来定义Field类型。 Like that you are more precise so that a radio field should have values for example:就像你更加精确,使无线电场应该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
  }
]

Playground Link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM