【发布时间】:2020-05-31 18:14:15
【问题描述】:
我有许多Item 对象和一个处理它们的方法。问题是某些项目可能具有其他项目没有的某些属性。
type ItemType = 'ApiGateway' | 'ApiGatewayEndpoint' | 'ApiGatewayMethod';
export default interface Item {
ref?: string;
position: Position;
type: ItemType;
children?: Item[];
}
function process(item: Item) {...}
现在,假设我想创建一个单独的接口ApiGatewayMethodItem(扩展Item),它有一个称为“方法”的附加字符串属性,表示它是GET 还是POST 或其他东西。有没有一种方法可以让我输入 process({type: 'ApiGatewayMethod'}) tsc 就会开始抱怨缺少的属性 method ?我知道 TS 对“条件类型”有很好的支持,但我以前没有使用过它们,我很难理解它们......
假设我有接口
interface ApiGatewayMethodItem extends Omit<Item, 'type'> {
type: 'ApiGatewayMethod';
method: string;
}
现在,当我调用process 函数时,我需要编译器抱怨method 属性在我不指定时丢失,但指定类型ApiGatewayMethod
【问题讨论】:
-
您希望所有
Items 都拥有method 属性吗?还是只有ApiGatewayMethodItem? -
没有。只有 ApiGatewayMethodItem 将具有属性
method。然后我将拥有ApiGatewayEndpointItem,它不会拥有method属性,但会拥有path。我知道我应该在我的流程函数 (typescriptlang.org/docs/handbook/release-notes/…) 上使用代码类型,但文档很难解读
标签: typescript typescript-typings