如何将接口的两个字段连接在一起,我有一个这样的接口:
export interface IContractKpi {
type: 'shipmentVolumes' | 'transitTime' | 'invoices';
visible: boolean;
content: IKpiContent;
}
export type IKpiContent =
| IKpiShipmentVolumeContent[]
| IKpiTransitTimeContent[]
| IKpiInvoicesContent;
我想做的是打字脚本知道:
当type
是'shipmentVolumes'
时,content
是IKpiShipmentVolumeContent[]
。
当type
是'transitTime'
时,content
是IKpiTransitTimeContent[]
。
当type
是'invoices'
时,content
是IKpiInvoicesContent
。
这种情况和我想要实现的是,我从后端得到了一个响应:
kpis: IContractKpi[]
我有一个接受kpi: IContractKpi
类型的组件该组件通过查找为每种类型呈现不同的组件表:
const lookup: Record<'shipmentVolumes' | 'transitTime' | 'invoices', VueComponent> = {
shipmentVolumes: KpiShipmentVolumes,
transitTime: KpiTransitTime,
invoices: KpiInvoices,
}
const kpiComponent = computed(() => lookup[kpi.type])
<template>
<component :is="kpiComponent" :content="kpi.content" /> <--- here I would like for typescript not be angry with me :D
</template>
我可以简化代码,但这并不理想。
<template>
<KpiShipmentVolumes v-if="kpi.type === 'shipmentVolumes'" :content="kpi.content" /> <--- this still makes it angry
<KpiTransitTime v-if="kpi.type === 'transitTime'" :content="kpi.content" />
<KpiInvoices v-if="kpi.type === 'invoices'" :content="kpi.content" />
</template>
您通常会使用并集,它表示所有有效状态。
export type IContractKpi = ({
type: 'shipmentVolumes'
content: IKpiShipmentVolumeContent[];
} | {
type: 'transitTime'
content: IKpiTransitTimeContent[];
} | {
type: 'invoices'
content: IKpiInvoicesContent[];
}) & {
visible: boolean;
}