Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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

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     } } 
like image 550
Hemant Avatar asked Dec 28 '17 12:12

Hemant


2 Answers

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

If you change your syntax to an arrow function, like

pages = () => { 

or simply omit the function keyword and arrow altogether, like

pages() { 

then the this object inside the function will reference the class instance this instead of type any.

See the TypeScript handbook for more explanation.

like image 200
Eric King Avatar answered Oct 02 '22 22:10

Eric King


Use explicit this annotation:

pages = function(this: BaseResult) { 

In this context, this is not an argument to the function but the actual place to declare the type of this, see the handbook:

The JavaScript specification states that you cannot have a parameter called this, and so TypeScript uses that syntax space to let you declare the type for this in the function body.

https://www.typescriptlang.org/docs/handbook/2/functions.html#declaring-this-in-a-function

like image 42
BOPOHOB Avatar answered Oct 02 '22 22:10

BOPOHOB