![](/img/trans.png)
[英]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.