typescript - 当同一接口上存在其他属性(字符串文字)时,有条件地使类型成为必需
问题描述
我正在使用 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
解决方案
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;
推荐阅读
- c# - 将 azure keyvault 机密 json 反序列化为 MicrosoftIdentityOptions
- php - 如何在一个 gcloud 应用上运行多个页面
- powershell - Set-PnPGroup : 找不到组
- python - Python中执行时间跟踪的效率
- python - Project Euler 问题 12,如何优化我的代码以便更快地找到答案?
- node.js - 如何查询文档中包含特定值的数组
- python - 在python中使用多进程时子进程会做什么
- c - 并行计算在 C 中使用 Petsc
- javascript - Ionic5 模态路由
- angular - Angular 在单独的线程中从后端获取数据