Skip to content

Instantly share code, notes, and snippets.

@nedarb
Last active November 17, 2022 23:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nedarb/fe41235a9e14ffe1d1c9cecda573a1ee to your computer and use it in GitHub Desktop.
Save nedarb/fe41235a9e14ffe1d1c9cecda573a1ee to your computer and use it in GitHub Desktop.
TypeScript utility types that aren't built into TypeScript
/**
* Make all properties in T required
*/
declare 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 NonStrict = { id: string } | { ns: string };
* // OK:
* const ok: NonStrict = { id: '123', ns: 'something' };
* type Strict = StrictUnion<{ id: string } | { ns: string }>;
* // ERROR:
* const err: Strict = { id: '123', ns: 'something' };
*/
declare type StrictUnion<T> = StrictUnionHelper<T, T>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment