#2759Medium

RequiredByKeys

Implement a generic `RequiredByKeys<T, K>` which takes two type argument `T` and `K`. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement RequiredByKeys<T, K> which makes only the specified keys of T required while leaving the rest unchanged, defaulting to making all properties required when K is not provided.

Challenge Instructions: RequiredByKeys

Medium

Implement a generic RequiredByKeys<T, K> which takes two type argument T and K.

K specify the set of properties of T that should set to be required. When K is not provided, it should make all properties required just like the normal Required<T>.

For example

interface User {
name?: string
age?: number
address?: string
}
 
type UserRequiredName = RequiredByKeys<User, 'name'> // { name: string; age?: number; address?: string }
 

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

Loading...

Detailed Explanation

type Merge<T> = { [K in keyof T]: T[K] }
 
type RequiredByKeys<T, K extends keyof T = keyof T> = Merge<
  Omit<T, K> & Required<Pick<T, K>>
>

How it works:

This challenge helps you understand selective property modifier manipulation and intersection type flattening 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