Created
February 17, 2023 21:18
-
-
Save braden-salesforce/577e00ac77bc5838ac97b2f9e411dbbb to your computer and use it in GitHub Desktop.
Typescript helper types
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 | |
*/ | |
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 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