Home > other >  React Typescript: Performing logic on multi-type array based on type
React Typescript: Performing logic on multi-type array based on type

Time:07-28

I have an array of both objects(JSX elements) and Strings. I want to iterate over the array and perform operations to the strings and skip the objects. What I have right now is this:

let arr = [...arrayOfStringAndObjects];

for (let i = 0; i < arr.length; i  ) {
  if (typeof arr[i] === "string") {
    arr[i].replace(regexForKeywordSearch, (match: string) => {
      return "123456789!@#$%^&*"   match   "123456789!@#$%^&*";
    });
    arr[i].split("123456789!@#$%^&*");
  } else {
    continue;
  }

essentially I am trying to cut out a string based on a list of keywords and splitting them (which I will flatten later). However Typescript is not allowing me to perform string methods throwing me this error : "Property 'replace' does not exist on type 'string | object'. Property 'replace' does not exist on type 'object'."

How can I allow typescript to ignore when the type:object is encountered in my loop?

CodePudding user response:

You can filter an array upfront and then work with strings only:

let arr = arrayOfStringAndObjects
  .filter((v) => typeof v === "string") as string[];

Also keep in mind that arr[i].replace and arr[i].split calls do not update an array elements. You can use an assignment arr[i] = arr[i].replace(...) or map method.

CodePudding user response:

Try

const mystring =  arr[i] as string;
mystring.replace(regexForKeywordSearch, ...

This is your way of telling typescript to interpret that variable as a string.

You already check the type of the object before forcing a type on a variable which is a good practice.

  • Related