首页 > 解决方案 > 当同一接口上存在其他属性(字符串文字)时,有条件地使类型成为必需

问题描述

我正在使用 Typescript 在 React 中创建一个通用表单字段,当前显示如下:

interface FieldProps {
    name: string;
    label: string;
    type: "email" | "text" | "textarea" | "select";
    options?: string[];
}

我正在尝试创建一个界面,这样如果用户提供"select"了道具,type那么应该需要 options 道具,并且 linter 会显示错误。对于所有其他类型,它应该没问题。

<Field name="email" label="Email" type="email"/> // should show no error
<Field name="country" label="Country" type="select"/> //should show error

标签: typescript

解决方案


This is where union types come in, you need to split your interface definition into specific use cases like so:

interface FieldPropsBase {
    name: string;
    label: string;
}

interface FieldPropsWithOptions extends FieldPropsBase {
    type: "select";
    options: string[];
}

interface FieldPropsWithoutOptions extends FieldPropsBase {
    type: "email" | "text" | "textarea";
    options?: string[];
}

type FieldProps = FieldPropsWithOptions | FieldPropsWithoutOptions;

推荐阅读