javascript - 如何按值定义类型?
问题描述
代码:
type InputProps = {
a: string;
};
type SelectProps = {
b: string;
};
type TypeProps = 'Input' | 'Select';
type ConfigProps = {
type: TypeProps;
componentProps: InputProps | SelectProps;
};
const config: ConfigProps = {
type: 'Input',
componentProps: {
a: 'demo'
}
};
如何定义ConfigProps
,如果type
道具值相等Input
则componentProps
应该是 InputProps
。
预计:
const config: ConfigProps = {
type: 'Input',
componentProps: {
b: 'demo' // ERROR, because type equal to 'Input', but InputProps just allow prop a
}
};
解决方案
您可以将您的类型定义为更明确的值:
type ConfigProps = {
type: 'Input';
componentProps: InputProps;
} | {
type: 'Select';
componentProps: SelectProps;
};
这种方式如果type
是'Input'
那么componentProps
必须是InputProps
推荐阅读
- lua - 制作衣服图形用户界面
- c# - Docker 无法为 DotNet Core 2.2 WebAPI 初始化 CoreCLR
- python - 用熊猫解析不一致的时间
- python - 有什么方法可以将 txt 文件列表(带有分割线)合并到 pandas 数据框中?
- google-apps-script - Google Web App 未能将光标正确放置在 Google 表格中
- ios - 滚动视图中未显示的图像(仅代码,无情节提要)
- python - 在 Pypher 中使用 Python 自动分配函数
- python - 为什么这个环视正则表达式返回意外结果?
- html - CSS为有角度的div添加阴影
- symfony - DQL-如何使用“&”运算符