TS2683:“this”隐式具有“any”类型,因为它没有使用“apply”的类型注释

Kev*_*off 4 this typescript

这个问题之前可能已经被问过,但我仍然无法在我的情况下解决它。

我正在尝试用 TypeScript 编写一个 memoize 函数,但无法this在函数内部输入内容

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;
    };
}
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

TS2683:“this”隐式具有类型“any”,因为它没有类型注释。

我不确定我是否理解如何输入this以及它的类型到底应该是什么

Apl*_*123 6

this您可以通过使用类型命名的“参数”来给出类型this。由于您不知道this会是什么(因为使用该函数的人可以在任何上下文中使用它),我建议unknown使用显式any类型(就我个人而言,我认为unknown更惯用):

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;
    };
}
Run Code Online (Sandbox Code Playgroud)