0

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?

  • Does this answer your question? [Why can Typescript not figure out the type in my code?](https://stackoverflow.com/questions/66233214/why-can-typescript-not-figure-out-the-type-in-my-code) – Jared Smith Jul 28 '22 at 00:21

2 Answers2

1

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.

Ivan Shumilin
  • 1,743
  • 3
  • 13
  • 18
0

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.

Awad Maharoof
  • 2,260
  • 1
  • 24
  • 36