Home > Software engineering >  Array filter in typescript?
Array filter in typescript?

Time:05-02

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.

CodePudding user response:

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

CodePudding user response:

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);
})
  • Related