Last active
October 26, 2023 13:56
-
-
Save albertms10/fb5a6d87a97db584086241d5bad74a41 to your computer and use it in GitHub Desktop.
TypeScript type that removes nullable properties from a collection (object or array)
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
/** | |
* Removes nullable properties (with `null` or `undefined` values) from an object or array. | |
* @template T The object or array to remove nullable properties from. | |
* @see https://gist.github.com/albertms10/fb5a6d87a97db584086241d5bad74a41 | |
* @example | |
* type A = { a?: string; b: null; c?: number | null }; | |
* type B = NonNullableCollection<A>; | |
* // { a: string; c: number; } | |
* @example | |
* type A = [string, undefined, number, null]; | |
* type B = NonNullableCollection<A>; | |
* // (string | number)[] | |
*/ | |
export type NonNullableCollection<T> = T extends (infer U)[] | |
? Exclude<U, null | undefined>[] | |
: { | |
[K in keyof T as NonNullable<T[K]> extends never ? never : K]-?: Exclude< | |
T[K], | |
null | undefined | |
>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment