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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.