【问题标题】:Missing index signature in type Array<string> with TypeScript使用 TypeScript 在类型 Array<string> 中缺少索引签名
【发布时间】:2018-03-23 08:45:38
【问题描述】:

我在 TypeScript 中看到了这个错误:

代码本身就是这样的:

let fn =  function (transformPaths: Array<string>, cb: Function) {

    async.mapLimit(transformPaths, 5, function (t: string, $cb: Function) {

         // ....

    }, cb);

};

错误信息是:

TS2345:“字符串 []”类型的参数不能分配给 输入“字典”。 'string[]' 类型中缺少索引签名。

我该如何纠正这个问题?从屏幕截图中可以看出,来自异步库的类型不喜欢将纯字符串数组作为第一个参数传递给 async.mapLimit,但为什么呢?

我 99% 确定我需要为字符串数组添加索引签名,但我该怎么做呢?

这是“编译”的东西,但我不知道它是否正确(这似乎对任何人都没有帮助):

export interface ISumanTransformPaths extends Array<string> {
  [index:string]: Object
}

现在当我使用(transformPaths: ISumanTransformPaths) 时,它会编译,但我不确定这是否正确。

【问题讨论】:

  • 您需要不同的类型。你有一个数组,你需要一个看起来像 js 的对象(即:{ key1: "value1", key2: "value2" }
  • @NitzanTomer 我不这么认为——我认为异步库将接受一个 Iterable,它可以是一个对象或数组。但我同意,这不是很清楚。
  • 我不知道这个async 库,但通常Dictionary 表示键/值。你能分享一个指向它的定义文件的链接吗?
  • 是的,我同意你的观点,我 99% 确定 Dictionary 意味着键/值。实际上,我现在坚信异步的 def 类型是不正确的。它应该是 Iterable 而不是 Dictionary。

标签: typescript typescript2.0


【解决方案1】:

signatures for this method 是:

mapLimit<T, R, E>(arr: T[] | IterableIterator<T>, limit: number, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
mapLimit<T, R, E>(arr: Dictionary<T>, limit: number, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;

因此它可以与Dictionary 或数组/IterableIterator 一起使用。
我不确定为什么编译器会推断出第二个签名而不是第一个签名,但可能是因为您传递的 callback 应该是第四个参数,而第三个需要是迭代器。

【讨论】:

  • 感谢 Nitzan,我想通了,我添加了一个答案,显示什么对我有用。
  • 我仍在寻找这个该死问题的答案:github.com/DefinitelyTyped/DefinitelyTyped/issues/24469
【解决方案2】:

感谢 Nitzan 确认 @types/async 可能是正确的。这解决了问题:

之前:

 let fn = function (transformPaths: Array<string>, cb: Function) {

    async.mapLimit(transformPaths, 5, function (t: string, cb: Function){

     // problem...does not compile

    }, cb);
 } 

之后:(仔细看,只有一个变化)

  let fn = function (transformPaths: Array<string>, cb: AsyncResultArrayCallback<Error,Array<any>>) {

        async.mapLimit(transformPaths, 5, function (t: string, cb: Function) {

        // now it compiles!

        }, cb);

   };

【讨论】:

    猜你喜欢
    • 2022-08-21
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 2016-10-31
    • 2020-01-17
    • 2018-11-10
    • 2019-04-20
    相关资源
    最近更新 更多