Last active
January 27, 2022 20:21
-
-
Save Aryaman1706/890fe31d771439bcbd2872899a780d68 to your computer and use it in GitHub Desktop.
TypeScript: RemoveUndefined Type
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 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