Last active
November 9, 2024 12:36
-
-
Save ashalfarhan/d56cedba041df4b9820c351cd2417e60 to your computer and use it in GitHub Desktop.
Typescript type utilities
This file contains hidden or 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
// Used for flatten complex object type | |
type Flatten<T> = { | |
[K in keyof T]: T[K]; | |
}; | |
// Set K as required | |
type RequiredPick<T, K extends keyof T> = Flatten< | |
{ | |
[P in K]-?: T[P]; | |
} & Omit<T, K> | |
>; | |
// Set K as non-nullable | |
type NonNullablePick<T, K extends keyof T> = Flatten< | |
{ | |
[P in K]-?: NonNullable<T[P]>; | |
} & Omit<T, K> | |
>; | |
// Set K as partial | |
type PartialPick<T, K extends keyof T> = Flatten< | |
{ | |
[P in K]?: T[P] | null; | |
} & Omit<T, K> | |
>; | |
// Set K as readonly | |
type ReadonlyPick<T, K extends keyof T> = Flatten< | |
{ | |
readonly [P in K]: T[P]; | |
} & Omit<T, K> | |
>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment