This question might have been asked before but I am still unable to fix it in my case.
I am trying to write a memoize function in TypeScript but have not been able to type this inside of my function
function memoize<T extends string | number, R>(fn: (args: T) => R): (args: T) => R {
const cache: { [key: string]: R } = {};
return function (...args): R {
if (cache[args.toString()]) {
return cache[args.toString()];
}
const result = fn.apply(this, args); // TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
cache[args.toString()] = result;
return result;
};
}
I get this error
TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
And I am not sure I understand how to type this and what exactly its type shoud be
You give this a type by having an "argument" named this with a type. Since you have no clue what this will be (since the person using the function can use it in any context), I'd suggest unknown or an explicit any type (personally, I think unknown is more idiomatic):
function memoize<T extends string | number, R>(fn: (args: T) => R): (args: T) => R {
const cache: { [key: string]: R } = {};
return function (this: unknown, ...args): R {
if (cache[args.toString()]) {
return cache[args.toString()];
}
const result = fn.apply(this, args);
cache[args.toString()] = result;
return result;
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With