Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to tell TypeScript compiler Array.prototype.filter removes certain types from an array?

Tags:

typescript

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.

like image 455
shuntksh Avatar asked Mar 24 '17 23:03

shuntksh


People also ask

How does TypeScript filter work?

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.

What is array prototype filter call?

prototype. filter() The filter() method creates a new array with all elements that pass the test implemented by the provided function.


1 Answers

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.

like image 50
theanurin Avatar answered Sep 21 '22 01:09

theanurin