鑒于此輸入:
export type Test = {
one: {
a: string;
b: string;
c: string;
};
two: {
a: string;
b: string;
d: string;
};
}
我需要一個像CombinedChildren<T>輸出以下型別的泛型:
export type Combined = {
a?: string;
b?: string;
c?: string;
d?: string;
}
基本上,它獲取 children 屬性并將它們組合起來,即使它們不存在于所有 children 中,也包括它們。
試過
export type KeyOfTest = Partial<Test[keyof Test]>
export type MappedKeyOfTest = Partial<{
[key in keyof Test[keyof Test]]: Test[keyof Test][key]
}>
但沒有一個輸出正是我想要的。
uj5u.com熱心網友回復:
我們可以將其分解為幾個步驟。首先,我們通過 得到所有子型別的聯合Test[keyof Test]。然后我們想要一個所有這些型別的聯合,所以我們使用一個實用程式型別將聯合型別轉換為交集型別(取自 @jcalz 的這個答案)。最后,我們應用Partial到結果型別。
export type Test = {
one: {
a: string;
b: string;
c: string;
};
two: {
a: string;
b: string;
d: string;
};
three: {
a: string;
e: number;
}
}
// union to intersection converter by @jcalz: https://stackoverflow.com/a/50375286/8580499
// Intersect<{ a: 1 } | { b: 2 }> = { a: 1 } & { b: 2 }
type Intersect<T> = (T extends any ? ((x: T) => 0) : never) extends ((x: infer R) => 0) ? R : never;
// Combined = { a?: string; b?: string; c?: string; d?: string; e?: number }
type Combined = Partial<Intersect<Test[keyof Test]>>;
游樂場鏈接
uj5u.com熱心網友回復:
如果您還想合并所有型別,例如 string | 數字那么這里是一個解決方案
export type Test = {
one: {
a: string;
b: string;
c: string;
};
two: {
a: number;
b: string;
d: string;
};
three: {
a: string;
e: number;
}
}
type AllNested = Test[keyof Test]
type KeyOf<T> = T extends any ? keyof T : never
type PropValue<T, K extends PropertyKey> = T extends Record<K, infer V> ? V : never
type Merged<T> = {
[P in KeyOf<T>] : PropValue<T, P>
}
type MergedType = Merged<AllNested>
鏈接到 游樂場
解決方案基于這個出色的答案
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/311190.html
