我有对象数组。数组中的每个对象代表一个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',
}
]
答案 0 :(得分:2)
我将建议您使用Field
和TextField
并扩展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
}
]