2

Here is my code:

let someVar: Array<string>;
somevar = ["a", "b", undefined, "c"].filter((it) => !!it);

Above code gives error

Type '(string | undefined)[]' is not assignable to type 'string[]'.
  Type 'string | undefined' is not assignable to type 'string'.
    Type 'undefined' is not assignable to type 'string'.

I am not sure how do I get rid of the error without changing the type of someVar.

My actual case is that the type of variable is coming from an entity class that takes either an array of strings or is null. And this best represents the model.

So how do I fix this without modifying the type of someVar?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
rahulserver
  • 10,411
  • 24
  • 90
  • 164
  • 1
    Does this answer your question? [Filter to remove undefined items is not picked up by TypeScript](https://stackoverflow.com/questions/57988567/filter-to-remove-undefined-items-is-not-picked-up-by-typescript) – jonrsharpe Jun 04 '21 at 12:00
  • yes @jonrsharpe, but I think the answer i accepted in this question is much easier for me and different than the one in that link. – rahulserver Jun 05 '21 at 02:02

2 Answers2

1

With a type guard:

function isDefined<T>(val: T | undefined | null): val is T {
    return val !== undefined && val !== null;
}
let someVar: Array<string>;
someVar = ["a", "b", undefined, "c"].filter(isDefined);
Roberto Zvjerković
  • 9,657
  • 4
  • 26
  • 47
1

Use as keyword to solve the problem.

let someVar: Array<string>;
someVar = ["a", "b", undefined, "c"].filter((it) => !!it) as string[];
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
  • 1
    The quickest solution! – rahulserver Jun 04 '21 at 12:22
  • The quickest solution.. and the dirtiest. This won't prevent you from adding other types to the array (like numbers, booleans,...), thereby loosing the type safety. Roberto Zvjerković' solution is much cleaner and should be the accepted answer. – fikkatra Jul 27 '23 at 10:53