typescript - 如何根据属性的值配置条件类型?
问题描述
我有许多Item
对象和处理它们的方法。问题是某些项目可能具有其他项目没有的某些属性。
type ItemType = 'ApiGateway' | 'ApiGatewayEndpoint' | 'ApiGatewayMethod';
export default interface Item {
ref?: string;
position: Position;
type: ItemType;
children?: Item[];
}
function process(item: Item) {...}
现在,假设我想创建一个单独的接口ApiGatewayMethodItem
(即 extends Item
),它有一个名为“方法”的附加字符串属性,表示它是 GET 还是 POST 或其他东西。有没有一种方法可以让我在输入process({type: 'ApiGatewayMethod'})
tsc 后立即开始抱怨缺少的属性method
?我知道 TS 对“条件类型”有很好的支持,但我以前没有使用过它们,而且我很难理解它们......
所以假设我有界面
interface ApiGatewayMethodItem extends Omit<Item, 'type'> {
type: 'ApiGatewayMethod';
method: string;
}
现在当我调用该函数时,我需要编译器在我不指定它时process
抱怨该属性丢失,而是指定类型method
ApiGatewayMethod
解决方案
您可以仅使用不具有属性“方法”的 2 个 ItemType 来定义您的项目类型。然后将属性 'method' 仅添加到类型 'ApiGatewayMethodItem'
type ItemType = 'ApiGateway' | 'ApiGatewayEndpoint';
export default interface DefaultItem {
ref?: string;
position: Position;
type: ItemType;
children?: DefaultItem[];
}
interface ApiGatewayMethodItem extends Omit<DefaultItem, 'type'> {
type: 'ApiGatewayMethod';
method: string;
}
type Item = DefaultItem | ApiGatewayMethodItem;
function process(item: Item) {
}
process ({
type: 'ApiGatewayMethod',
position: null
})
推荐阅读
- html - 在 CSS 中,用内联 SVG 替换光标,不使用填充属性
- jgit - 如何使用 JGit 将所有文件(添加、修改、删除)添加到索引?
- sql - 在这种情况下如何防止被0除?
- azure - ARM 模板:存储帐户函数应用作为事件处理程序的事件网格订阅配置失败
- python - 如何让 Python 中的 textwrap 打破下划线或任意字符(不仅仅是连字符和空格)
- selenium - 如何使用 Selenium 单击包含特定文本的类
- c# - 如何为 VST 插件(如 VST.NET 2 主机中的 vsthost 配置)设置采样率和缓冲区大小
- python - 使用python和正则表达式去除单词中的重复字符串
- java - 在启用 TLS 的情况下使用 kafka-topics cli 命令时出现问题
- mysql - 如何在一行中获得不同的值以及它们各自的平均值作为 mySQL 中的输出