#3543•Extreme

CombineObjectChildren

Merge the child objects of a type into one. Keys every child shares stay required, the rest become optional, which takes a distributive conditional to collect.

CombineObjectChildren<T> takes an object whose values are themselves objects and squashes them into a single shape. A key that appears in every child stays required. A key that only some children have becomes optional. Where several children declare the same key with different types, the result is the union of those types. Think of the three response shapes an endpoint can return, folded into one type you can hand to a consumer that does not care which branch it got.

type Test = {
  one: { a: string; b: string; c: string }
  two: { a: string; b: string; d: string }
  three: { a: string; b: string; e: string }
}
 
type Result = CombineObjectChildren<Test>
// { a: string; b: string; c?: string; d?: string; e?: string }

Challenge Instructions: CombineObjectChildren

Extreme

Output an object which contains all keys present in every children object and as optional all the others.

For example, given this input:

type Test = {
one: {
a: string;
b: string;
c: string;
};
two: {
a: string;
b: string;
d: string;
};
three: {
a: string;
b: string;
e: string;
};
}

output

type CombineObjectChildren<Test> = {
a: string;
b: string;
c?: string;
d?: string;
e?: string;
}

View on GitHub: https://tsch.js.org/3543

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
/* _____________ Your Code Here _____________ */

type CombineObjectChildren<T> = any

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '../helpers'

type Question = {
    one: {
        a: string;
        b: string;
        c: string;
    };
    two: {
        a: string;
        b: string;
        d: string;
    };
    three: {
        a: string;
        b: string;
        e: string;
    };
}

type Answer = {
    a: string;
    b: string;
    c?: string;
    d?: string;
    e?: string;
}

type cases = [
  Expect<Equal<Answer, CombineObjectChildren<Question>>>,
 

Pro Challenge

Get access to all 200+ challenges, including every medium, hard, and extreme one.

One-time payment, lifetime access. 30-day money-back guarantee.

Detailed Explanation

The solution in full:

type Children<T> = T[keyof T]
 
type SharedKeys<T> = keyof Children<T>
 
type AllKeys<T> = Children<T> extends infer C
  ? C extends unknown
    ? keyof C
    : never
  : never
 
type ValueAt<T, K> = Children<T> extends infer C
  ? C extends unknown
    ? K extends keyof C
      ? C[K]
      : never
    : never
  : never
 
type Flatten<T> = { [K in keyof T]: T[K] }
 
type CombineObjectChildren<T> = Flatten<
  { [K in SharedKeys<T>]: ValueAt<T, K> } & {
    [K in Exclude<AllKeys<T>, SharedKeys<T>>]?: ValueAt<T, K>
  }
>

Every step after the first line hangs on one idea: keyof over a union gives you the keys the union members agree on, and you need a conditional type to get the rest.

Two different key sets

T[keyof T] throws away the outer names and leaves the union of the children. For the example above that is { a, b, c } | { a, b, d } | { a, b, e }.

Applied directly to that union, keyof does not hand back every key. It hands back the ones that are safe to read from any member, which is the intersection:

type Shared = keyof ({ a: string; b: string } | { a: string; d: string })
// 'a'

That is exactly the required half of the answer, so SharedKeys<T> needs no extra work. The optional half needs the opposite: the union of all keys. To get it, the conditional type in AllKeys splits the union apart first. A naked type parameter on the left of extends distributes, so C extends unknown ? keyof C : never is evaluated once per member and the results are joined back into a union:

// keyof { a: string; b: string } -> 'a' | 'b'
// keyof { a: string; d: string } -> 'a' | 'd'
// result: 'a' | 'b' | 'd'

The Children<T> extends infer C wrapper exists only to give the union a parameter name. infer C in a top-level conditional always matches, so the branch is unconditional, and C is then naked and free to distribute on the next line. Without that detour there is no type parameter to distribute over.

Reading a value that not every child has

For a shared key, a plain indexed access already does the right thing. Children<T>['b'] reads b from each member and unions the results, which is why the fifth test expects string | number.

For a key like d that only one child declares, the indexed access is not even legal: d is not in keyof Children<T>. Writing it as a conditional does not help either, because the guard fails as a whole:

type Naive<T, K> = K extends keyof Children<T> ? Children<T>[K] : never
// Naive<Test, 'c'> -> never

ValueAt distributes first and asks the question per child. Children that lack the key contribute never, children that have it contribute their type, and never disappears from a union:

// ValueAt<Test, 'c'> asks each child in turn
// { a, b, c } has 'c' -> string, the other two -> never
// result: string

Building the two halves

With both key sets in hand the shape writes itself. One mapped type over SharedKeys<T> with no modifier, one over everything else with ?:

type Required_ = { [K in 'a' | 'b']: ValueAt<Test, K> }
// { a: string; b: string }
type Optional_ = { [K in 'c' | 'd' | 'e']?: ValueAt<Test, K> }
// { c?: string; d?: string; e?: string }

Exclude<AllKeys<T>, SharedKeys<T>> is what separates them. When every child has the same keys, that subtraction is never, and a mapped type over never is the empty object type {}, which contributes nothing to the intersection. The second test goes the other way: the two children share no key at all, SharedKeys<T> is never, and the required half is the one that vanishes.

Why the intersection is not the answer yet

Required_ & Optional_ describes the right thing, but Equal in the tests compares types structurally and an intersection is not the same type as the object it is equivalent to:

type Inter = { b: string } & { d?: number }
type Check = Equal<Inter, { b: string; d?: number }> // false

Flatten<T> is the fix. Mapping [K in keyof T] over a type parameter is homomorphic, which means TypeScript copies the ? and readonly modifiers of each property instead of dropping them. The intersection is resolved into one flat object, the optional markers survive, and Equal is satisfied.

Edge cases the tests cover

This challenge is originally from here.

Share this challenge

Related Challenges

Learn the Concepts

Become a TypeScript Pro

Track your progress through 200+ hands-on challenges. Free, sign in with GitHub.

Or start solving right away: explore all TypeScript challenges