#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).

Loading...

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

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount