I am trying to filter null (undefined) element from an array by using Array.prototype.filter but TypeScript compiler does not seem to recognize the derived array of the "filter" function and failed to pass type check.
Assuming following simplified code where I have an array with (number|undefined)[] types and want to filter undefined to fit into a number[] array.
const arry = [1, 2, 3, 4, "5", 6]; const numArry: number[] = arry .map((i) => { return typeof i === "number" ? i : void 0; }) .filter((i) => i);
Error says:
Type '(number | undefined)[]' is not assignable to type 'number[]'. Type 'number | undefined' is not assignable to type 'number'. Type 'undefined' is not assignable to type 'number'.
I can cast the resulted array to number[] like below knowing filter function removes undefined.
const arry = [1, 2, 3, 4, "5", 6]; const numArry: number[] = (arry .map((i) => { return typeof i === "number" ? i : void 0; }) .filter((i) => i) as Number[]);
Is there a better way to achieve this other than casting?
Environment: TSC2.1 with strictNullChecks enabled.
In Typescript, Filter() is a built-in array method which is defined as a method for creating a new array or set of elements that contains a subset of the given array elements by returning the array of all the values of the elements in the newly created sub-array over the given array.
prototype. filter() The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Use User-Defined Type Guards feature of TypeScript:
const arry = [1, 2, 3, 4, "5", 6]; const numArry: number[] = arry .filter((i): i is number => { return typeof i === "number"; }); // numArry = [1, 2, 3, 4, 6]
Take a look at i is number
in the callback function. This trick gives us ability to cast a type of the Array.filter result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With