Skip to content

Instantly share code, notes, and snippets.

@ashalfarhan
Last active October 18, 2023 11:09
Show Gist options
  • Save ashalfarhan/d56cedba041df4b9820c351cd2417e60 to your computer and use it in GitHub Desktop.
Save ashalfarhan/d56cedba041df4b9820c351cd2417e60 to your computer and use it in GitHub Desktop.
Typescript type utilities
// Used for making complex object type
// to be plain object
type Flatten<T> = {
[K in keyof T]: T[K];
};
// Partially making field `K` required,
// and should be the keyof `T`
type RequiredPick<T, K extends keyof T> = Flatten<
{
[P in K]-?: T[P];
} & Omit<T, K>
>;
// Partially making field `K` non nullable,
// and should be the keyof `T`
type NonNullablePick<T, K extends keyof T> = Flatten<
{
[P in K]-?: NonNullable<T[P]>;
} & Omit<T, K>
>;
// Partially making field `K` optional,
// and should be the keyof `T`
type PartialPick<T, K extends keyof T> = Flatten<
{
[P in K]?: T[P] | null;
} & Omit<T, K>
>;
// Partially making field `K` readonly,
// and should be the keyof `T`
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