Reputation:
I have a small React + Typescript application. I am running a filtering function which is executed when some buttons are clicked or a value is entered into an input.
I have interfaces everywhere. I also passed the interface to the state, or the fact that I will have an empty array. But I keep getting an error with the following text:
"TS2345: Argument of type 'TodoItemInterface[] | undefined' is not assignable to parameter of type 'TodoItemInterface[]'. Type 'undefined' is not assignable to type 'TodoItemInterface[]'."
I can’t find how and where to pass that I definitely won’t have undefined or fix this error in a different way. Please help. Below I send the code of the function in useEffect and functions with a state that are related to it.
error is thrown here in filterItems.
useEffect(() => {
const newArray = searchInputFilter(filterItems(todoListStateArray, infoSearchObject.filter), textForSearch);
setVisibleTodoListItems(newArray);
}, [infoSearchObject, todoListStateArray, textForSearch])
Another code
const filterItems = (arr: TodoItemInterface[], filter: string) => {
if (filter === 'all') {
return arr;
} else if (filter === 'active') {
return arr.filter((item) => (!item.done));
} else if (filter === 'done') {
return arr.filter((item) => item.done);
}
};
const searchInputFilter = (arr: TodoItemInterface[], search: string) => {
if (search.length === 0) {
return arr;
}
return arr.filter((item) => {
return item.subtitle.toLowerCase().includes(search.toLowerCase());
});
}
const [infoSearchObject, setInfoSearchObject] = useState({inWork: '', done: '', filter: 'all'});
const [todoListStateArray, setTodoListStateArray] = useState<TodoItemInterface[] | []>(todoListDefault);
const [visibleTodoListItems, setVisibleTodoListItems] = useState<TodoItemInterface[] | []>(todoListDefault);
const [textForSearch, setTextForSearch] = useState('');
Upvotes: 0
Views: 2159
Reputation: 1768
That is actually one of the benefits in using typescript; It’s actually telling you there is the possibility that your filterItems
can possibly return undefined
, and that happens when neither of your conditions are true.
As a solution, you should add a return value when none of the conditions are met:
const filterItems = (arr: TodoItemInterface[], filter: string): TodoItemInterface[] => {
if (filter === 'all') {
return arr;
} else if (filter === 'active') {
return arr.filter((item) => (!item.done));
} else if (filter === 'done') {
return arr.filter((item) => item.done);
}
return arr;
};
To note that in the example I also added a return type to your function; That is pretty important to ensure consistency in what get actually returned from it.
Upvotes: 0