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;
};