Typescript “我该怎么做?”;联合国索引;a型?

Typescript “我该怎么做?”;联合国索引;a型?,typescript,Typescript,我试图理解如何“取消索引” 鉴于: type Example = { sayHi: { name: string; } | { sayHi: string; }; cure: { bool: boolean; } | { cure: string; }; } 如何获得: ({name: string; } | { sayHi: string; }) & ({bool: boo

我试图理解如何“取消索引”

鉴于:

type Example = {
    sayHi: {
        name: string;
    } | {
        sayHi: string;
    };
    cure: {
        bool: boolean;
    } | {
        cure: string;
    };
}
如何获得:

({name: string; } | { sayHi: string; }) & ({bool: boolean } | { cure: string })
我试过了,但它把一切都变成了联盟

type Example2 = Example[keyof Example]
我们可以使用的变体分布在与属性值相交的类型的键上:

type Example = {
    sayHi: {
        name: string;
    } | {
        sayHi: string;
    };
    cure: {
        bool: boolean;
    } | {
        cure: string;
    };
}


type UnionToIntersectionValues<U, K extends keyof U = keyof U> = 
    (K extends unknown ? (k: U[K]) => void : never) extends ((k: infer I) => void) ? I : never

type R = UnionToIntersectionValues<Example>
// type R = ({
//     name: string;
// } & {
//     bool: boolean;
// }) | ({
//     name: string;
// } & {
//     cure: string;
// }) | ({
//     sayHi: string;
// } & {
//     bool: boolean;
// }) | ({
//     sayHi: string;
// } & {
//     cure: string;
// })

类型示例={
早希:{
名称:字符串;
} | {
早喜:弦;
};
治疗:{
布尔:布尔;
} | {
治疗:字符串;
};
}
类型UnionToIntersectionValues=
(K扩展未知?(K:U[K])=>void:never)扩展((K:inferi)=>void)?I:从来没有
类型R=UnionToIntersectionValues
//R型=({
//名称:字符串;
// } & {
//布尔:布尔;
// }) | ({
//名称:字符串;
// } & {
//治疗:字符串;
// }) | ({
//早喜:弦;
// } & {
//布尔:布尔;
// }) | ({
//早喜:弦;
// } & {
//治疗:字符串;
// })


注意:Ts将根据
(A | B)和(C | D)
(A&C)|(A&D)|(B&C)|(B&D)
的等价性,将交叉点移到内部,并将联合点移到外部,因此
R
的类型与您正在寻找的类型是等价的。

这非常简洁,我试图用递归类型对键进行迭代,这需要联合到元组&这通常是一个更糟糕的答案。我遇到了一个问题,如果对象为空,它将返回unknown。如果未知,我只需要发送
U
。@ThomasReggi我想这可以在额外的检查中处理。像
keyu这样的东西永远不会扩展?“someDefaultType”:UnionToIntersectionValues