Skip to content

Instantly share code, notes, and snippets.

@braden-salesforce
Created February 17, 2023 21:18
Show Gist options
  • Save braden-salesforce/577e00ac77bc5838ac97b2f9e411dbbb to your computer and use it in GitHub Desktop.
Save braden-salesforce/577e00ac77bc5838ac97b2f9e411dbbb to your computer and use it in GitHub Desktop.
Typescript helper types
/**
* Make all properties in T required
*/
type MakeRequired<T, K extends keyof T> = {
[P in K]-?: T[P];
} & Omit<T, K>;
type UnionKeys<T> = T extends T ? keyof T : never;
type StrictUnionHelper<T, TAll> = T extends any
? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, undefined>>
: never;
/**
* This allows union types that are "strict" or exclusive - making all extra properties never'ed.
*
* @example
* type NonStrictUnion = { id: string } | { ns: string };
* const ok: NonStrictUnion = { id: '123', ns: 'something' }; // VALID but unexpected because it's ambiguous as to which of the union types it is.
* type Strict = StrictUnion<{ id: string } | { ns: string }>;
* const err: Strict = { id: '123', ns: 'something' }; // ERROR
*/
type StrictUnion<T> = StrictUnionHelper<T, T>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment