Skip to content

Instantly share code, notes, and snippets.

@albertms10
Last active October 26, 2023 13:56
Show Gist options
  • Save albertms10/fb5a6d87a97db584086241d5bad74a41 to your computer and use it in GitHub Desktop.
Save albertms10/fb5a6d87a97db584086241d5bad74a41 to your computer and use it in GitHub Desktop.
TypeScript type that removes nullable properties from a collection (object or array)
/**
* 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