Yuzhe's Blog

yuzhes

ToPrimitive

ToPrimitive

Problem Link

Problem

Convert a property value recursively into a primitive type.

type X = {
  name: 'Tom',
  age: 30,
  married: false,
  info: {
    additional1: null,
    additional2: undefined
  }
}

type Expected = {
  name: string,
  age: number,
  married: boolean,
  info: {
    additional1: null,
    additional2: undefined
  }
}

type Todo = ToPrimitive<X> // Expected

Solution

type ToPrimitive<T> =
  T extends object
    ? T extends (...args: any[]) => any
      ? Function
      : { [K in keyof T]: ToPrimitive<T[K]> }
    : T extends string
      ? string
      : T extends number
        ? number
        : T extends boolean
          ? boolean
          : T extends symbol
            ? symbol
            : T extends bigint
              ? bigint
              : T

How it works:

  1. If T is a function, map it to Function.
  2. If T is an object (non-function), recursively map each property.
  3. For primitives, widen the literal type to its base primitive ('Tom'string, 30number, etc.).
  4. null and undefined fall through to T unchanged.

Key Takeaways