TypeScript filter zeros from an array

TypeScript, --strictNullChecks mode.

Suppose I have an array of null strings (string | null) []. What would be a single expression method to remove all zeros so that the result has a string like []?

const array: (string | null)[] = ["foo", "bar", null, "zoo", null]; const filterdArray: string[] = ???; 

Array.filter does not work here:

 // Type '(string | null)[]' is not assignable to type 'string[]' array.filter(x => x != null); 

Arrays may work, but they are not supported by TypeScript.

In fact, the question can be generalized to the problem of filtering an array of any type of union by deleting records from one union from one element. But let me focus on joins with null and possibly undefined, as these are the most common use cases.

+5
source share
3 answers

You can use the predicate type in .filter to avoid giving up strict type checking:

 function notEmpty<TValue>(value: TValue | null | undefined): value is TValue { return value !== null && value !== undefined; } const array: (string | null)[] = ['foo', 'bar', null, 'zoo', null]; const filteredArray: string[] = array.filter(notEmpty); 

Alternatively, you can use array.reduce<string[]>(...) .

+5
source

You can apply the filter result to the type you want:

 const array: (string | null)[] = ["foo", "bar", null, "zoo", null]; const filterdArray = array.filter(x => x != null) as string[]; 

This works for the more general use case you mentioned, for example:

 const array2: (string | number)[] = ["str1", 1, "str2", 2]; const onlyStrings = array2.filter(x => typeof x === "string") as string[]; const onlyNumbers = array2.filter(x => typeof x === "number") as number[]; 

( code on the playground )

+4
source

I believe that everything is fine with you, except that type checking only makes the filter type different from the return type.

 const array: (string | null)[] = ["foo", "bar", null, "zoo", null]; const filterdArray: string[] = array.filter(f => f !== undefined && f !== null) as any; console.log(filterdArray); 
0
source

Source: https://habr.com/ru/post/1266127/


All Articles