filter in typescript got error of '(string | null)[]' is not assignable

Viewed 1357

I have an array of object, one of the property has a null value, I used filter to remove it, but typescript give me warning null is not assignable? since filter will never return null why typescript give me such an error?

const data = [
  {
    id: "123"
  },
  {
    id: "456"
  },
  {
    id: null
  }
];

const d2: string[] = data.map((d) => d.id).filter((o) => o);

console.log(d2);

demo https://codesandbox.io/s/gallant-water-vio56?file=/src/index.ts:0-165

1 Answers

Typescript can't figure out that .filter((o) => o) will narrow the types of the array, not without some help. You can define a custom type guard and use that though. For example:

function notNull<T>(val: T | null): val is T {
    return val !== null;
}

const d2 = data.map((d) => d.id).filter(notNull); // d2 is a string[]

Or an inline version that only works with strings:

const d2 = data.map(d => d.id).filter((o): o is string => !!o);

Playground link

Related