Skip to content

Instantly share code, notes, and snippets.

@janv
Last active November 18, 2017 12:53
Show Gist options
  • Save janv/193ee3aa3f020128cd0264383b9307b7 to your computer and use it in GitHub Desktop.
Save janv/193ee3aa3f020128cd0264383b9307b7 to your computer and use it in GitHub Desktop.
// The following helpers were found at
// https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-319495340
/**
* From https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-307871458
* The Diff type is a subtraction operator for string literal types. It relies on:
* - T | never = T
* - T & never = never
* - An object with a string index signature can be indexed with any string.
*/
declare type StringDiff<T extends string, U extends string> = ({[K in T]: K} &
{[K in U]: never} & {[K: string]: never})[T];
/**
* From https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-311923766
* Omits keys in K from object type T
*/
declare type ObjectOmit<T extends object, K extends keyof T> = Pick<T, StringDiff<keyof T, K>>;
/**
* Returns a version of type T where all properties which are also in U are optionalized.
* Useful for makding props with defaults optional in React components.
* Compare to flow's $Diff<> type: https://flow.org/en/docs/types/utilities/#toc-diff
*/
declare type ObjectDiff<T extends object, U extends object> = ObjectOmit<T, keyof U & keyof T> &
{[K in (keyof U & keyof T)]?: T[K]};
/**
* A more relaxed version of ObjectOmit, that allows you to kill any keys from an object,
* not just the onces that exist on it
*/
declare type ObjectOmitAny<T, K extends string> = Pick<T, StringDiff<keyof T, K>>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment