Typescript error ts(2769) in array filter function when in if block that checks for type previously

Viewed 11

I would like to know why typescript complains that moveInDate property is possibly string | undefined when it is nested inside if block that checks whether or not that property is truthy. In code below you can see that when console logging it is type string but when looping an array with .filter function it reads it as string | undefined.

I know that there is multiple ways of getting around this e.g new Date(filters.moveInDate!); or new Date(filters.moveInDate as string); . Even defining a new variable const date = filters.moveInDate above .filter block and then using it inside .filter as return new Date(date). But I want to understand why is this error happening in the first place?

Code in question

export interface IStateFilters {
  moveInDate?: string;
}

const arr = [1, 2, 3];

export const filter = (filters: IStateFilters) => {
  if (filters.moveInDate) {
    console.log(filters.moveInDate); // <- it is string over here

    return arr.filter((apt) => {
      return new Date(filters.moveInDate); // why is it string | undefined here?
    });
  }

  return arr;
};

Link to sandbox

1 Answers

It seems that TypeScript loses the type narrowing when you use filter:

export interface IStateFilters {
  moveInDate?: string;
}

const arr = [1, 2, 3];

export const filter = (filters: IStateFilters) => {
  if (typeof filters.moveInDate === 'undefined') return arr;
  const moveIndate: string = filters.moveInDate;
  return arr.filter((apt: number) => new Date(moveIndate)); // just string now
};

Possibly this might help answer it more:

TypeScript: Why is that my filter method cannot narrow the type and eliminate the undefined and false from the array

https://github.com/microsoft/TypeScript/issues/16069

Related