Issue
Given this input:
export type Test = {
one: {
a: string;
b: string;
c: string;
};
two: {
a: string;
b: string;
d: string;
};
}
I need a generics like CombinedChildren<T>
which outputs the following type:
export type Combined = {
a?: string;
b?: string;
c?: string;
d?: string;
}
Basically, it takes the children properties and combines them, including them even if they're not present in all children.
Tried
export type KeyOfTest = Partial<Test[keyof Test]>
export type MappedKeyOfTest = Partial<{
[key in keyof Test[keyof Test]]: Test[keyof Test][key]
}>
But none output exactly what I want.
Solution
In case you want to also merge all types for example string | number then here is a solution
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>
Link to the playground
Solution is based on this brilliant answer
Answered By - ZZB
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.