'Array filter in typescript?
I have to filter array in typescript.
const { movies, message } = useAppSelector(state => state.movies);
//Here movies is array getting from backend
Here I have to filter it in typescript.
I have code in javascript.
const mathches = movies.filter(movie => {
const escapeRegExp = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
const regex = new RegExp(escapeRegExp(search), "gi");
return movie.name.match(regex);
})
I can't understand how can define type here.
Here I get some error when I paste it in ts file-
Property 'filter' does not exist on type 'never'.
Parameter 'movie' implicitly has an 'any' type.
Parameter 'str' implicitly has an 'any' type.
Please help me to define type here.
Solution 1:[1]
You can define a type for movies:
interface MovieType { name: string }
Then change the filter as
const mathches = movies.filter((movie:MovieType) => {
const escapeRegExp = (str: any) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
const regex = new RegExp(escapeRegExp(search), "gi");
return movie.name.match(regex);
})
Edit: as per the question change
You can update movies as follows:
const movies = useAppSelector<MovieType[]>(state => state.movies);
Solution 2:[2]
Maybe try using this
const movies: Array<{name: string}> = [
{name: "The great wall"},
{name: "Moon Knight"},
{name: "Kong: Skull Island"},
{name: "Morbius"}
]
const mathches = movies.filter((movie: any) => {
const escapeRegExp = (str: any) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
const regex = new RegExp(escapeRegExp(search), "gi");
return movie.name.match(regex);
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Zulfiqar Ali |
