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

时间:2020-10-01 08:58:07

标签: typescript typescript-typings typescript-generics

我有对象数组。数组中的每个对象代表一个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',
  }
]

1 个答案:

答案 0 :(得分:2)

我将建议您使用FieldTextField并扩展RadioField接口的联合来定义FieldCommon类型。这样一来,您就可以更加精确,例如,无线电字段应该具有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