【问题标题】:Why can't I use this inside function?为什么我不能使用这个内部函数?
【发布时间】:2019-04-18 05:51:52
【问题描述】:

代码:

const f: any = function(...args: any[]) {
    const a = this;
};

错误:

semantic error TS2683 'this' implicitly has type 'any' because it does not have a type annotation.

【问题讨论】:

标签: typescript typescript-decorator


【解决方案1】:

您启用了noImplicitThis 编译器选项,并且在新的f 函数this 表达式中隐式具有any 类型 - 因此出现错误。

要修复它 - 只需使用 "fake" this parameter 明确指定类型:

const f: any = function(this: typeof target, ...args: any[]) {
    // ...
};

默认情况下,函数中 this 的类型是 any。从 TypeScript 2.0 开始,您可以提供显式的 this 参数。这个参数是函数参数列表中最先出现的假参数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    相关资源
    最近更新 更多