33763-hard-union-to-object-from-key

Back

type UnionToObjectFromKey<Union, Key> = Union extends Union
  ? Key extends keyof Union
    ? Union
    : never
  : never

Solution by Sun79 #35025

type UnionToObjectFromKey<U, K extends PropertyKey> =  U extends {[P in K]?: unknown}
  ? {} extends U ? never : U
  : never;

If the key should be required:

type UnionToObjectFromKey<U, K extends PropertyKey> = U extends {[P in K]: unknown} ? U : never;

Solution by alexandroppolus #35023

type UnionToObjectFromKey<Union, Key>
  // Step 1: This is a self-reference check that always evaluates to true.
  // It is used to distribute the conditional type over a union.
  // i.e. if `U = 1 | 2`, then `[U]` is `[1 | 2]`
  // and `U extends U ? [U] : never` will be evaluated as `[1] | [2]`
  = Union extends Union
    // Step 2: Check if `Key` is a key of `Union`. If yes, proceed to the next step.
    // i.e. if `Key = 'foo'`, then `Key extends keyof {foo: 1} ? true : false` will be evaluated as `true`
    ? Key extends keyof Union
      // Step 3: If all previous conditions are met, return `Union`.
      ? Union
    // Step 2: If `Key` is not a key of `Union`, return `never`.
    : never
  // Step 1: This will never be reached because `Union extends Union` is always true.
  : never

Playground

Solution by teamchong #35018