【问题标题】:Cannot pass array of string to function无法将字符串数组传递给函数
【发布时间】:2018-03-15 03:34:51
【问题描述】:

我有这个功能:

function proc(unames: Array<string>){}

我尝试通过它:

  import _ = require('lodash');

  const usernames = _.flattenDeep([unames]).filter(function (item, index, arr) {
     return item && arr.indexOf(item) === index;
  });

  const recipient = 'foobarbaz';
  proc(usernames.concat(recipient));

我收到此错误:

有人知道如何缓解这种情况吗?

我试过这个,我得到一个更长更疯狂的错误:

function proc(unames: Array<string | ReadonlyArray<string>>){}

但是,这使错误消失了:

function proc(unames: Array<string | ReadonlyArray<any>>){}

不太清楚发生了什么。

【问题讨论】:

    标签: node.js typescript lodash typescript2.0 tsc


    【解决方案1】:

    警告似乎是指使用.concat() 而不是proc()

    当在 Array(例如 usernames)上调用时,TypeScript 会验证提供给 .concat() 的参数是否也是 Arrays。

    要解决警告,您有几个选择:

    • 由于您使用的是 Lodash,它自己的 _.concat() 允许附加单个值,TypeScript 的验证应该意识到这一点:

      const recipient = 'foobarbaz';
      proc(_.concat(usernames, recipient));
      
    • recipient 定义为Array 或在调用.concat() 时将其包装起来:

      const recipient = [ 'foobarbaz' ];
      proc(usernames.concat(recipient));
      
      const recipient = 'foobarbaz';
      proc(usernames.concat( [recipient] ));
      
    • 您还可以配置 TypeScript 以验证更高版本的 ECMAScript。在标准的5.12015 (6th edition) 之间,内置.concat() 的行为已更改为支持单个值(通过检测可扩展)。

      目前,TypeScript 正在为 5.1 或更早版本验证 .concat()

    【讨论】:

    • @AlexanderMills 对不起。更正:该方法现在确实支持单个值(从 ECMAScript 2015 或第 6 版开始),但是 TypeScript 仍然仅在参数为数组时才认为它有效。
    • 是的,这很奇怪,好像[].concat('foo')已经被JS支持了一段时间了
    • @AlexanderMills 这可能是可配置的,可能与构建输出的目标有关,并且仅数组只是最高兼容性的默认设置。
    猜你喜欢
    • 2014-09-06
    • 1970-01-01
    • 2016-12-08
    • 2016-12-03
    • 2015-09-09
    • 1970-01-01
    • 2013-06-27
    相关资源
    最近更新 更多