程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了TS2683:“this”隐式具有类型“any”,因为它没有使用“apply”的类型注释大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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

开发过程中遇到TS2683:“this”隐式具有类型“any”,因为它没有使用“apply”的类型注释的问题如何解决?下面主要结合日常开发的经验,给出你关于TS2683:“this”隐式具有类型“any”,因为它没有使用“apply”的类型注释的解决方法建议,希望对你解决TS2683:“this”隐式具有类型“any”,因为它没有使用“apply”的类型注释有所启发或帮助;

这个问题以前可能有人问过,但我仍然无法解决这个问题。

我正在尝试在 TypeScript 中编写备忘录函数,但无法在我的函数内键入 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;
    };
}

我收到此错误

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

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

解决方法

您通过使用一个名为 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;
    };
}

大佬总结

以上是大佬教程为你收集整理的TS2683:“this”隐式具有类型“any”,因为它没有使用“apply”的类型注释全部内容,希望文章能够帮你解决TS2683:“this”隐式具有类型“any”,因为它没有使用“apply”的类型注释所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: