代码之家  ›  专栏  ›  技术社区  ›  mles

类型“string[][]不能分配给类型“string[]”

  •  0
  • mles  · 技术社区  · 6 年前

    tagsUnparsed 像绳子一样 "a b c d+e+f" . 我需要一个数组应该是:

    ["a", "b", "c", "d", "e", "f"]

    在Typescript中,我尝试了:

    let tags: string[] = tagsUnparsed.split(' ');
    tags = tags.map((tag: string) => {
      return tag.split('+')
    });
    

    我得到这个错误:

    Type 'string[][]' is not assignable to type 'string[]'.
      Type 'string[]' is not assignable to type 'string'.ts(2322)
    

    我不知道 string[][] 来自。 .map 返回一个数组,不确定类型定义错误的原因。

    0 回复  |  直到 6 年前
        1
  •  2
  •   Michal    6 年前

    可以使用RegExp(空格或加号)作为分隔符:

    const tagsUnparsed = "a b c d+e+f"
    tagsUnparsed.split(/[ +]/) // ["a", "b", "c", "d", "e", "f"]
    

    错误是因为您有 space 分隔字符串,然后按 + ,因此您有字符串数组或数组:

    ["a", "b", "c", "d+e+f"]
    ["a", "b", "c", ["d", "e", "f"]]
    
        2
  •  3
  •   baao    6 年前

    split返回一个数组,使map返回一个数组数组。你可以简单地使用 flatMap 而不是 map ,或附加 flat() 之后 地图 .

    推荐文章