Reputation: 117
I wanted to have shared utility function for dumping many scattered objects in the code like below, but it generates a TypeScript error. Is there any way to do this without repeating the shared code? I tried this and this. It seems to work fine in Chrome browser JS.
function formatthis() { return JSON.stringify(this); }
...
function whatever() {
...
var something = { aa:234, bb:123, toString:formatthis };
...
var something2 = { dfwerg:22, wer:11, toString:formatthis };
...
var something3 = { sergw:55, qsfds:33, toString:formatthis };
...
console.log('looks like '+something);
...
}
UPDATE: Example updated to stress reuse of method(s) among different random objects. It appears to work in Chrome browser (globally, in functions, with "use strict", etc), but // @ts-ignore always compiles but does not always work in Node, not sure why.
Upvotes: 1
Views: 5926
Reputation: 1028
As other commenters have suggested, rather than ignoring the issue, you should declare this
as a parameter of your function. Something like:
function formatthis(this: unknown) {
return JSON.stringify(this);
}
Upvotes: 2