首页 > 解决方案 > 如何根据属性的值配置条件类型?

问题描述

我有许多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抱怨该属性丢失,而是指定类型methodApiGatewayMethod

标签: typescripttypescript-typings

解决方案


您可以仅使用不具有属性“方法”的 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
})

推荐阅读