【发布时间】:2019-06-11 00:35:53
【问题描述】:
我正在尝试制作某种解析器,用于解析数据字段,并将其制成完整的形式并进行显示。 fields 属性将定义客户端将从url 属性IForm 接收的json 数据数组中的每个字段
表单界面示例如下:
export interface IForm {
name: string;
url: string;
fields: IField<any>[] // <-- What is the proper type of this?
}
export interface IField<T> {
name: string;
label: string;
mandatory?: boolean;
default: T;
}
export interface IInput<T> extends IField<T> {
type: 'input'
}
export interface IOptionsUrl {
url: string;
idField: string;
labelField: string;
}
export interface IOptionsList<T> {
id: T;
label: string;
}
export interface IOptions<T> extends IField<IOptionsList<T>> {
type: 'options';
options?: IOptionsUrl | IOptionsList<T>[] | string[];
multiple?: boolean;
}
export interface ICheckbox extends IField<boolean> {
type: 'checkbox'
}
IForm 的fields 属性将包含多个类型,例如IField<string> 或IField<number> 等。它们由每种类型中的type 属性确定,全部基于 IField。所以我不确定是否应该输入<any>,因为它将在数组中包含多种类型的数据。定义它的正确方法是什么?还是我应该一起跳过泛型而只使用任何泛型?
样本数据如下:
let meta: IForm = {
name: 'employee',
url: '/api/employee',
fields: [
{
type: 'input',
name: 'id',
label: 'Employee ID',
default: 0,
mandatory: true
},
{
type: 'input',
name: 'name',
label: 'Employee Name',
default: '',
mandatory: true
},
{
type: 'options',
name: 'gender',
label: 'Male/Female',
default: 'male',
options: ['Male', 'Female']
},
{
type: 'checkbox',
name: 'active',
label: 'Active',
default: true
},
{
type: 'options',
name: 'department',
label: 'Department',
default: 0,
options: {
url: '/api/departments',
idField: 'id',
labelField: 'name'
}
}
]
}
员工界面将是:
export interface IEmployee {
id: number;
name: string;
gender: string;
active: boolean;
department: number;
}
我应该如何定义 IForm 的接口?
谢谢
【问题讨论】:
-
IField<any>[]和Array<IField<any>>are synonymous according to the Array documentation。您可以创建自己的Union Type / Type Alias,例如type formType = string | number | boolean | date;。然后使用IField<formType>。 -
是的,但是
将在一个数组中同时包含所有这些字符串、数字、布尔值和日期。 -
any涵盖 更多 而不仅仅是这 4 个,所以如果你想要类型安全,请不要使用any。 -
你打算如何使用
IForm?您期望其fields属性提供什么类型的保证?也许您可以将其编辑为minimal reproducible example,以便有人可以建议您做什么。还有更多的强类型解决方案,其中IForm本身就是通用的,但根据您的用例,可能不需要复杂性。 -
@jcalz 刚刚添加了示例数据。
标签: typescript