Skip to content

Instantly share code, notes, and snippets.

@jbaez
Last active February 2, 2022 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbaez/71df88c473629af75f11b404122fb09d to your computer and use it in GitHub Desktop.
Save jbaez/71df88c473629af75f11b404122fb09d to your computer and use it in GitHub Desktop.
Useful Typescript global types

global.d.ts

// Returns the optional keys of T as a union of string literals
declare type OptionalKeys<T> = Exclude<
  {
    [K in keyof T]: T extends Record<K, T[K]> ? never : K;
  }[keyof T],
  undefined
>;

// Makes all optional properties in T required
declare type OptionalParams<T> = Required<Pick<T, OptionalKeys<T>>>;

// Returns a Readonly type with all optional properties in T required
declare type OptionalDefaults<T> = Readonly<OptionalParams<T>>;

// Returns a Readonly type with all optional properties in T required excluding keys from K
declare type OptionalDefaultsPartial<T, K extends keyof T> = Omit<
  OptionalDefaults<T>,
  K
>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment