Last active
November 17, 2022 23:25
-
-
Save nedarb/fe41235a9e14ffe1d1c9cecda573a1ee to your computer and use it in GitHub Desktop.
TypeScript utility types that aren't built into TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Make all properties in T required | |
*/ | |
declare type MakeRequired<T, K extends keyof T> = { | |
[P in K]-?: T[P]; | |
} & Omit<T, K>; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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