#16259Medium

ToPrimitive

Convert a property of type literal (label type) to a primitive type. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement ToPrimitive<T> which deeply converts all literal types in an object to their corresponding primitive types (e.g., 'Tom' becomes string, 30 becomes number).

Challenge Instructions: ToPrimitive

Medium

Convert a property of type literal (label type) to a primitive type.

For example

type X = {
name: 'Tom',
age: 30,
married: false,
addr: {
home: '123456',
phone: '13111111111'
}
}
 
type Expected = {
name: string,
age: number,
married: boolean,
addr: {
home: string,
phone: string
}
}
type Todo = ToPrimitive<X> // should be same as `Expected`

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

ChallengeSolution
type PersonInfo = {
  name: 'Tom'
  age: 30
  married: false
  addr: {
    home: '123456'
    phone: '13111111111'
  }
  hobbies: ['sing', 'dance']
  readonlyArr: readonly ['test']
  fn: () => any
}

type ExpectedResult = {
  name: string
  age: number
  married: boolean
  addr: {
    home: string
    phone: string
  }
  hobbies: [string, string]
  readonlyArr: readonly [string]
  fn: Function
}

type cases = [Expect<Equal<ToPrimitive<PersonInfo>, ExpectedResult>>]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

type Primitive<T> = T extends string
  ? string
  : T extends number
    ? number
    : T extends boolean
      ? boolean
      : T extends Function
        ? Function
        : T extends object
          ? ToPrimitive<T>
          : T
 
type ToPrimitive<T> = T extends readonly any[]
  ? { [K in keyof T]: Primitive<T[K]> }
  : {
      [K in keyof T]: T[K] extends object ? ToPrimitive<T[K]> : Primitive<T[K]>
    }

How it works:

This challenge helps you understand recursive type transformation and literal-to-primitive type widening and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge

Learn the Concepts