Created
March 14, 2023 18:34
-
-
Save tscpp/9a30e038ef4efe5df1c5ce147dcd97c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Wether the property is optional in the object or not. | |
* | |
* @example ``` | |
* type Foo = PropertyRequirement<{ a: number }, 'a'>; // 'required' | |
* type Bar = PropertyRequirement<{ b?: number }, 'b'>; // 'optional' | |
* ``` | |
*/ | |
type PropertyRequirement<T, K extends keyof T> = Pick<T, K> extends Required< | |
Pick<T, K> | |
> | |
? 'required' | |
: 'optional'; | |
/** | |
* Wether any of the properties of the object is required. | |
* | |
* @example ``` | |
* type Foo = ObjectRequirement<{ a: number; b: number }> // 'required' | |
* type Bar = ObjectRequirement<{ a: number; b?: number }> // 'required' | |
* type Baz = ObjectRequirement<{ a?: number; b?: number }> // 'optional' | |
* ``` | |
*/ | |
type ObjectRequirement<T> = { | |
[K in keyof T]-?: PropertyRequirement<T, K>; | |
}[keyof T] extends 'optional' | |
? 'optional' | |
: { [K in keyof T]-?: PropertyRequirement<T, K> }[keyof T] extends | |
| 'optional' | |
| 'required' | |
? 'required' | |
: 'required'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment