简体   繁体   English

React+Typescript:基于类型对多类型数组执行逻辑

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

I have an array of both objects(JSX elements) and Strings.我有一个对象(JSX 元素)和字符串的数组。 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'."但是 Typescript 不允许我执行字符串方法,这会抛出这个错误:“'string | object' 类型上不存在属性 'replace'。'object' 类型上不存在属性 'replace'。”

How can I allow typescript to ignore when the type:object is encountered in my loop?当我的循环中遇到 type:object 时,如何允许 typescript 忽略?

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.还要记住arr[i].replacearr[i].split调用不会更新数组元素。 You can use an assignment arr[i] = arr[i].replace(...) or map method.您可以使用赋值arr[i] = arr[i].replace(...)map方法。

Try尝试

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

This is your way of telling typescript to interpret that variable as a string.这是您告诉 typescript 将该变量解释为字符串的方式。

You already check the type of the object before forcing a type on a variable which is a good practice.在对变量强制使用类型之前,您已经检查了 object 的类型,这是一个很好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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