元素隐式具有“any”类型,因为类型“typeof globalThis”没有索引签名

Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature

提问人:devguy 提问时间:4/20/2020 最后编辑:j3ffdevguy 更新时间:4/21/2020 访问量:11198

问:

我正在尝试获取以下代码以在 TypeScript 中编译和运行。

我不确定为什么给我带来问题。如果我在纯 JavaScript 中尝试这个,我被告知这不是一个函数?funcMapthis.funcMap.k1

const obj = {

  foo: function () { console.log("foo") },
  bar: function () { console.log("bar") },

  funcMap: {
    k1: this.foo,
    k2: this.bar
  },

  dump: function () {
    this.funcMap.k1();    // --> foo
    this.funcMap["k2"](); // --> bar
  }

}

obj.dump();

错误消息为:

main.ts:7:14 - error TS7017: Element implicitly an 'any' type 
because type 'typeof globalThis' no index signature.

7     k1: this.foo,
               ~~~

main.ts:8:14 - error TS7017: Element implicitly an 'any' type 
because type 'typeof globalThis' no index signature.

8     k2: this.bar
               ~~~
打字稿

评论


答:

3赞 user2541867 4/20/2020 #1

这是因为对象内部的关键字不是这个对象本身,它是全局上下文,例如在浏览器或 node.js 中。thiswindowglobal

this将指向函数内部的对象,但不作为对象属性。

为了修复您的代码,我会将这些函数移动到单独的常量中:

const foo = function () { console.log("foo") }
const bar = function () { console.log("bar") }

const obj = {
  foo, // shortcut for foo: foo
  bar,

  funcMap: {
    k1: foo,
    k2: bar
  },

  dump: function () {
    this.funcMap.k1();    // --> foo
    this.funcMap["k2"](); // --> bar
  }

}

obj.dump();

评论

0赞 devguy 4/21/2020
好的,现在它是有道理的,我有一种预感,这与“这个”有关,但只是无法弄清楚对象属性的原因。我确实想出了一个替代解决方案,我最终将 funcMap 变成了一个函数来返回映射的对象。
0赞 devguy 4/21/2020 #2

我最终选择了以下解决方案。它是将 funcMap 更改为返回映射对象的函数。

“User2541867”也提供了一个答案,但是您可能无法或不想将函数移动到全局空间中。

const obj = {

  foo: function () { console.log("foo") },
  bar: function () { console.log("bar") },

  funcMap: function () {
    return {
      k1: this.foo,
      k2: this.bar
    }
  },

  dump: function () {
    const mapped = this.funcMap();
    mapped.k1();    // --> foo
    mapped["k2"](); // --> bar
  }

}

obj.dump();