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 } }
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With