Reputation: 771
I am trying to get the following code to compile and run in TypeScript.
I am not sure why funcMap
is giving me problems. If I try this in pure JavaScript, I am told that this.funcMap.k1
is not a function?
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();
The error message is:
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
~~~
Upvotes: 2
Views: 12028
Reputation: 771
I ended up going with the following solution. It was to change funcMap into a function to return the mapping object.
"user2541867" also provided an answer, however it might be the case you cannot or do not want to move the function into the global space.
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();
Upvotes: 0
Reputation: 444
It is because this
keyword inside object is not this object itself, it is global context such as window
in browsers or global
in node.js.
this
will point to object inside a function, but not as object property.
To fix your code I'd move those functions to separate constants:
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();
Upvotes: 3