Skip to content

Instantly share code, notes, and snippets.

@Aryaman1706
Last active January 27, 2022 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aryaman1706/890fe31d771439bcbd2872899a780d68 to your computer and use it in GitHub Desktop.
Save Aryaman1706/890fe31d771439bcbd2872899a780d68 to your computer and use it in GitHub Desktop.
TypeScript: RemoveUndefined Type
type RemoveUndefined<T extends any[]> =
T extends (infer R | undefined)[]
? R[]
: T
// OK
type ArrayWithoutUndefined1 = RemoveUndefined<(string | number | undefined | Date)[]>
type ArrayWithoutUndefined2 = RemoveUndefined<(string | number | Date)[]>
type ArrayWithoutUndefined3 = RemoveUndefined<["hello", 1, 2, undefined, Date, {}]> // order is not maintained
type ArrayWithoutUndefined4 = RemoveUndefined<["hello", 1, 2, Date, {}]> // order is not maintained
const arr1 = [undefined, 1, 2, 3, "hello", "world", new Date()];
type ArrayWithoutUndefined5 = RemoveUndefined<typeof arr1>
const arr2 = [1, 2, 3, "hello", "world", new Date()];
type ArrayWithoutUndefined6 = RemoveUndefined<typeof arr2>
type ArrayWithoutUndefined7 = RemoveUndefined<[]>
// Not OK
type FailedArrayWithoutUndefined1 = RemoveUndefined<number>;
type FailedArrayWithoutUndefined2 = RemoveUndefined<string>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment