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

Hem*_*ant 9 typescript

我正在使用TypeScript文件遇到此问题,并想知道如何解决这个问题.

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

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

Eri*_*ing 19

正如某些注释所示,您的this引用未输入,因为您使用function () {}语法来定义函数.this这样一个函数内部的对象本身就是类型any,因为this它将是函数的调用者(在设计时不可知).

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

pages = () => {
Run Code Online (Sandbox Code Playgroud)

或者简单地省略函数关键字和箭头,比如

pages() {
Run Code Online (Sandbox Code Playgroud)

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

有关更多说明,请参阅TypeScript手册.

  • 请注意,如果您确实需要调用者指定的“ this”(例如,将框架设置“ this”为明智的框架将调用您的函数),则可以通过引入伪造的“ this”来告知TypeScript“ this”的类型。参数:`callback = function(this:HTMLElement){…}` (4认同)

BOP*_*HOB 8

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