我有以下内容:
type Original = {
checklist: FetchStates;
workflowFormInfo: FetchStates;
transitions: FetchStates;
}
type FinalResult = {checklist: FetchStates} | { workflowFormInfo: FetchStates} | { transitions: FetchStates}
如何将原始格式转换为最终结果,这样我就不需要手动在两侧创建每个条目了?
FinalResult是“计算”类型。
谢谢
答案 0 :(得分:0)
我在另一个StackOverflow answer中发现了RequireOnlyOne
类型。
使用它,您可以执行以下操作:
type RequireOnlyOne<T, Keys extends keyof T = keyof T> =
Pick<T, Exclude<keyof T, Keys>>
& {
[K in Keys]-?:
Required<Pick<T, K>>
& Partial<Record<Exclude<Keys, K>, undefined>>
}[Keys]
type Original = {
checklist: FetchStates;
workflowFormInfo: FetchStates;
transitions: FetchStates;
}
type FinalResult = RequireOnlyOne<Original>
const res1: FinalResult = {} // error
const res2: FinalResult = { checklist } // ok
const res3: FinalResult = { workflowFormInfo } // ok
const res4: FinalResult = { transitions } // ok
const res5: FinalResult = { checklist, workflowFormInfo } // error