Skip to content

Instantly share code, notes, and snippets.

@tscpp
Created March 14, 2023 18:34
Show Gist options
  • Save tscpp/9a30e038ef4efe5df1c5ce147dcd97c4 to your computer and use it in GitHub Desktop.
Save tscpp/9a30e038ef4efe5df1c5ce147dcd97c4 to your computer and use it in GitHub Desktop.
/**
* 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