typescript TS2683 (TS) 'this' 隐式具有类型 'any',因为它没有类型注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48007891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:51:09  来源:igfitidea点击:

TS2683 (TS) 'this' implicitly has type 'any' because it does not have a type annotation

typescript

提问by Hemant

I'm facing this problem with TypeScript file and would like to know how to fix this.

我正面临 TypeScript 文件的这个问题,想知道如何解决这个问题。

For now I have suppressed this typescript exception but would like to learn how to address this. The following is my code:

现在我已经抑制了这个打字稿异常,但想学习如何解决这个问题。以下是我的代码:

export class BaseResult {
    isSuccessful: boolean;
    totalRecords: number;
    successMessage: string;
    reasonForFailure: string;
    lastExecutedDateTime: Date;
}

export class Result<T> extends BaseResult {
    data: T;
}

export class CollectionResult<T> extends BaseResult {
    data: T[];
}

export class PagedCollectionResult<T> extends CollectionResult<T> {
    pageNumber: number;
    pageSize: number;
    filter: string;

    pages = function () {
        return (this.totalRecords <= 0 || this.pageSize <= 0) ? 0 : Math.ceil(this.totalRecords / this.pageSize);//<--All the **this** keyword shows the error
    }
}

回答by Eric King

As some of the comments indicated, your thisreference is not typed because you are using the function () {}syntax to define your function. The thisobject inside such a function will inherently be of type any, because thiswill be the caller of the function (unknowable at design-time).

正如一些评论所指出的,您的this引用没有键入,因为您正在使用function () {}语法来定义您的函数。this此类函数内的对象本质上是 类型any,因为this它将是函数的调用者(在设计时不可知)。

If you change your syntax to an arrow function, like

如果您将语法更改为箭头函数,例如

pages = () => {

or simply omit the function keyword and arrow altogether, like

或者干脆完全省略 function 关键字和箭头,例如

pages() {

then the thisobject inside the function will reference the class instance thisinstead of type any.

那么this函数内的对象将引用类实例this而不是 type any

See the TypeScript handbookfor more explanation.

有关更多解释,请参阅TypeScript 手册

回答by BOPOHOB

Use explicit thisannotation: pages = function(this: BaseResult) {

使用显式this注释:pages = function(this: BaseResult) {