可以使用联合类型和交叉类型来定义FieldProps
。联合类型用来定义各种元素的不同属性类型,交叉类型则用来将这些属性类型组合到一起。
例如,假设我们有两种元素:Input
和Select
,它们分别具有不同的属性。那么我们可以这样定义FieldProps
:
type InputProps = {
type: "text" | "password";
label: string;
};
type SelectProps = {
options: string[];
label: string;
};
type FieldProps = {
name: string;
} & (InputProps | SelectProps);
这里,我们首先定义了InputProps
和SelectProps
分别表示Input
和Select
元素所具有的不同属性。然后,我们使用交叉类型&
将它们与一个name
属性组合在一起,构成了FieldProps
类型。
现在,我们可以在我们的表单组件中使用FieldProps
类型了:
function InputField(props: FieldProps) {
if (props.type === "text") {
return (
);
} else if (props.type === "password") {
return (
);
}
}
function SelectField(props: FieldProps) {
return (
);
}
这里,InputField
和SelectField
都接收一个FieldProps
类型的参数,并根据不同的属性类型进行渲染。
这种方法可以轻松地扩展