Type Challenges: Implement the RequiredByKeys<T, K> Utility Type
The Built-In Required Generic Are Not Flexible, the RequiredByKeys Generics Come to the Rescue.

Welcome to the Mastering TypeScript series, there are dozens of articles in this series. To help readers better consolidate their knowledge of TypeScript, I have selected a few dozen challenges from the type-challenges repository on Github to complete the type challenge with you.
- Type Challenges: Implement the Built-In Pick
Utility Type - Type Challenges: Implement the Built-In Omit
Utility Type
Challenge
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 }Solution
Our type challenge is to implement the RequiredByKeys<T, K> generic, when K is not provided, it should make all properties required just like the normal Required<T>. So let’s first understand what Required<T> generic does.
Required<T>
Constructs a type consisting of all properties of Type set to required. The opposite of Partial.

Required<T> is TypeScript’s built-in utility type, which is defined in the typescript/lib/lib.es5.d.ts file:
/**
* Make all properties in T required.
* typescript/lib/lib.es5.d.ts
*/
type Required<T> = {
[P in keyof T]-?: T[P];
};The Required<T> generic uses TypeScript’s mapped type internally, and its syntax is as follows:

Where P in K is similar to the JavaScript for...in statement, which is used to iterate through all types in type K, and the type variable T, which is used to represent any type in TypeScript.

You can also use the additional modifiers read-only and question mark (?) in the mapping process. The corresponding modifiers are added and removed by adding the plus(+) and minus(-) prefixes. The default is to use the plus sign if no prefix is added.
After introducing the relevant knowledge of mapped types, the idea of implementing the RequiredByKeys generic is very simple.

As can be seen from the above figure, we only need to select the properties associated with K, set them as required and generate a new object type, then build another object type based on the remaining properties, and finally use the & operator to convert the above two object types are combined into a new object type.
If you want to learn more about intersection types, you can read this article.
Complete code
Finally, let’s look at the complete code:

