[英]Setting a dynamic or conditional value of an interface property in typescript
[英]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
接口的TextField
和RadioField
的联合来定义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.