Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS2683: 'this' implicitly has type 'any' because it does not have a type annotation using `apply`

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

like image 560
Kevin Amiranoff Avatar asked Oct 14 '25 08:10

Kevin Amiranoff


1 Answers

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;
    };
}
like image 131
Aplet123 Avatar answered Oct 18 '25 08:10

Aplet123