简体   繁体   中英

React+Typescript: Performing logic on multi-type array based on type

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM