【问题标题】:typescript Element implicitly has an 'any' type because expression of type 'string'typescript 元素隐式具有“任何”类型,因为“字符串”类型的表达式
【发布时间】:2021-10-27 12:48:01
【问题描述】:

我想动态地将项目添加到我的对象中

  twit: {
    accessTokenKey: [user::1xxxxxxxxxxxxxxxxx,user::1xxxxxxxxxxxxxxxxx],
    accessTokenSecret: [user::1xxxxxxxxxxxxxxxxxxxxxx,user::1xxxxxxxxxxxxxxxxxxxxxx],
    consumerKey: [user::1xxxxxxxxxxxxxxxxxxxxxxxx,user::1xxxxxxxxxxxxxxxxxxxxxxxx],
    consumerSecret: [user::1xxxxxxxxxxxxxxxxxxxxxxx,user::1xxxxxxxxxxxxxxxxxxxxxxx],
    tweetTags: [user:1xxxxxxxxxxxxxxxxxxxxxxx,user:1xxxxxxxxxxxxxxxxxxxxxxx]
  },

  function keys(
  twit: any
): string[] {
    Object.keys(notifications).map(function(x: string){
      if(Array.isArray(notifications[x])){

      notifications[x].map(function(k: string){
        var test = k.split('::')
        if(test[0] != '' || test[1] != ''){

          test[0] = test[0] == 'test:ser' ? test[0].replace(':','_') : test[0]

          notifications[test[0] + '_' + x ] = test[1]
        }
      })
      }
    })

  return twit

}

output is

  twit: {
    accessTokenKey: [user::1xxxxxxxxxxxxxxxxx,user::1xxxxxxxxxxxxxxxxx],
    accessTokenSecret: [user::1xxxxxxxxxxxxxxxxxxxxxx,user::1xxxxxxxxxxxxxxxxxxxxxx],
    consumerKey: [user::1xxxxxxxxxxxxxxxxxxxxxxxx,user::1xxxxxxxxxxxxxxxxxxxxxxxx],
    consumerSecret: [user::1xxxxxxxxxxxxxxxxxxxxxxx,user::1xxxxxxxxxxxxxxxxxxxxxxx],
    tweetTags: [user:1xxxxxxxxxxxxxxxxxxxxxxx,user:1xxxxxxxxxxxxxxxxxxxxxxx]
    accessTokenKey
    user1_accessTokenSecret:xxxxxxxxxxxxxxxxxxxx,
    user1_consumerKey:xxxxxxxxxxxxxxxxxxxx,
    user1_consumerSecret:xxxxxxxxxxxxxxxxxxxx,
    user1_tweetTags:xxxxxxxxxxxxxxxxxxxx,
    user2_accessTokenSecret:xxxxxxxxxxxxxxxxxxxx,
    user2_consumerKey:xxxxxxxxxxxxxxxxxxxx,
    user2_consumerSecret:xxxxxxxxxxxxxxxxx,xxx,
    user2_tweetTags:xxxxxxxxxxxxxxxxxxxx
  },

如果我稍后会使用该对象,我会收到类型错误:

元素隐式具有“任意”类型,因为“字符串”类型的表达式不能用于索引类型“”

请帮忙

【问题讨论】:

    标签: javascript typescript typeerror


    【解决方案1】:

    错误提示您给定的索引类型(字符串)不能用作索引类型。

    这个错误的原因是你的对象没有真正的索引签名。一个常见的解决方案是使用keyof typeof

    例子:

    const func = (s: keyof typeof myObject) => {
        myObject[s] = '123';
    }
    

    这个例子不会出错,因为我们告诉 TypeScript 我们的索引类型是我们对象的键。

    此外,您可以将对象的类型调整为Record<string, any>。这也将解决错误。

    const myObject: Record<string, any> = { ... };
    

    TypeScript Playground Reproduction

    【讨论】:

      猜你喜欢
      • 2020-11-13
      • 2019-12-17
      • 2021-08-16
      • 2021-05-04
      • 2021-02-28
      • 2021-12-31
      • 2021-10-11
      • 2017-03-14
      相关资源
      最近更新 更多