首页 > 解决方案 > 如何将索引签名分配给对象的值?

问题描述

给出以下代码:

  export function objToStr(object: object): string {

    let str = [];

    for (let p in object) {
      if (object.hasOwnProperty(p)) {
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(object[p]))
      }
    }


    return str.join("&")
  }

我从以下错误中得到错误object[p]

Element implicitly has an 'any' type because type '{}' has no index signature. [7017]

我试过了

 encodeURIComponent((<any>object[p]))

 encodeURIComponent(object[p]: any)

但我仍然得到错误。我发现打字一切都很混乱,那里有很多类型。

如果有人能告诉我 Typescript 想从我那里得到什么,那会很有帮助,这是最后一条错误消息,然后我将代码从 JS 切换到 TS。

编辑

我必须添加"noImplicitAny": true以测试设置,因为我不确定正在做什么以及代码将如何对其做出反应。

把它变成假我现在得到:

Argument of type 'string' is not assignable to parameter of type 'never'. [2345]对于现场部分str.push

标签: typescript-typings

解决方案


出现错误是因为您compilerOptions.noImplicitAny = true在 tsconfig.json 中有。如错误所示,将索引签名添加到object变量:

let object: { [index: string]: any } = {};
let str: string[] = [];

ieany将被明确指定。


推荐阅读