Specifying the type of "this" within the function body

After going through the typescript documentation, I came across an example that explains how to use type with this in a callback function. I am hoping someone can assist me in comprehending how this callback will operate.

interface DB {
  filterUsers(filter: (this: User) => boolean): User[];
}
 
const db = getDB();
const admins = db.filterUsers(function (this: User) {
  return this.admin;
});

Answer №1

When it comes to traditional functions and methods, this acts as a read-only parameter passed to the function by the calling code. You can find more information on this topic here. Essentially, when the function is executed, this refers to whatever the caller has specified explicitly or implicitly.

In TypeScript, using the this pseudo-parameter allows you to specify the type that this will have when the function is invoked. For example, in the DB interface, the filterUsers method specifies that this will be a reference to a User object during the callback.

You don't need to restate this type information in your callback function because TypeScript can infer it from the DB interface's declaration:

const db = getDB();
const admins = db.filterUsers(function() {
  return this.admin;
});

In one of the comments, you asked:

How does the function become bound to a specific User instance here?

The logic inside the filterUsers method ensures that when the callback is called, it sets the context (this) to a user object. This might involve using Function.prototype.call or Function.prototype.apply:

// Hypothetical snippet for a `filterUsers` method:
filterUsers(callback: (this: User) => boolean): User[] {
    const filtered = this.users.filter(user => callback.call(user));
    return filtered;
}

Using .call or .apply allows you to explicitly define the context for a function call.


It's worth mentioning that defining DB's filterUsers method in this way is not typically how interfaces would handle such behavior. It would be more conventional for the user to be passed as a regular argument, similar to how Array.prototype.filter works. However, this unconventional approach is used in documentation examples for explanatory purposes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Making a quick stop in Istanbul and NYC to collect a few important files

Setting up Istanbul/Nyc/Mocha for test coverage in my project has been a bit of a challenge. While I was successful in running Nyc, I noticed that not all the .ts files in my project were being picked up for test coverage. When I execute npm run coverag ...

Error message: Unable to locate Bootstrap call in standalone Angular project after executing 'ng add @angular/pwa' command

Having an issue while trying to integrate @angular/pwa, it keeps showing me an error saying "Bootstrap call not found". It's worth mentioning that I have removed app.module.ts and am using standalone components in various places without any module. Cu ...

"The ion-label in Ionic2 is cutting off some of the text and not displaying it

I'm currently facing an issue with ion-label inside ion-item. The description is not properly displaying and instead, it shows dot-dot.. ..I need the entire text to be visible. Is there any solution available? <ion-card *ngFor="let product of prod ...

summing 3 numbers to a total of 100 percent

I am currently trying to calculate the percentages of different statuses based on 3 count values. Let's assume I have 3 statuses: 1) Passed 2) Failed 3) Skipped When dealing with only two cases, I was able to use a combination of the Floor and Ceil ...

In ReactJS, the way to submit a form using OnChange is by utilizing the

Is there a way to submit a form using Onchange without a button? I need to fire the form but can't insert routes as it's a component for multiple clients. My project is built using react hook forms. const handleChange = (e: any) => { c ...

In Typescript, is it possible to utilize the value from a particular key in a type declaration as the type for another key within the same declaration?

Consider a scenario where I am designing a Variable type that includes a key named type with a value of type string. Is there a method to extract the value from the type key and utilize it as the type for another key within the declaration, without resorti ...

Strategies for preventing multi-level inheritance of TypeScript class properties and methods

In my current JavaScript class structure, the DataService is defined as follows: // data.service.ts export class DataService { public url = environment.url; constructor( private uri: string, private httpClient: HttpClient, ) { } ...

Utilizing data from the home component in another component: A guide

Here is the code I am working with, showcasing how to utilize (this.categoryType) in another component: getCategoryDetails(){ return this.http.get('ip/ramu/api/api/…') .map((res:Response) => res.json()); } The above code snippet is utilize ...

Error: The function call does not match any of the overloads. 'VueRouter' is not recognized

I'm new to TypeScript and currently trying to implement vue-router in my project. Encountering the following errors: Error TS2769: No overload matches this call in source\app\main.ts(3,3). Overload 1 of 3, '(options?: ThisTypedCompon ...

ngPrime table column selection and data extraction

I am looking to extract multiple columns from a table. Can anyone suggest the best approach for this? Does NGPrime offer any functionality for achieving this task? Appreciate your help! ...

Oops! An issue occurred during the `ng build` command, indicating a ReferenceError with the message "Buffer is not defined

I'm facing an issue while trying to utilize Buffer in my angular component ts for encoding the Authorization string. Even after attempting npm i @types/node and adding "node" to types field in tsconfig.json, it still doesn't compile with ng buil ...

What is the best way to allow the browser to either download a file or open it in a new tab based on what is feasible? (while maintaining the actual file

Currently in my web application, which utilizes Angular for the front-end and .Net Core for the back-end, there is a page where users can click on server-side stored files. The desired behavior is for the file to open directly in a new tab if the browser a ...

Having difficulty in utilizing localStorage to update the state

I've attempted to log back in using the stored credentials, however it's not working despite trying everything. The dispatch function is functioning properly with the form, but not when accessing localStorage. App.tsx : useEffect(() => { ...

What steps can be taken to initiate Nx Release on the apps/* when modifications are made to the connected libs/* modules?

Trying out the nx release command but struggling to get it to release an app when there are changes to a dependent module. Examining the graph below, you can see that I have 3 apps, with 2 depending on the shared-ui module. If I directly modify the apps, ...

Dynamic rows in an Angular 2 Material data table

I'm currently working on dynamically adding rows to an Angular 2 Data Table ( https://material.angular.io/components/table/overview) by utilizing a service called "ListService". This service provides me with the columns ("meta.attributes") to be displ ...

The modal popup feature is dysfunctional within the hierarchical component structure of angular-bootstrap-md

In my project, there is a structured hierarchy of components that includes: Agent task-list (utilizing the shared task-list-table component) task-type (as a separate component) preview-task (a modal component) agent.component.html (where task-type, ta ...

Challenge with Typescript Interfaces

Can someone help me with understanding interfaces in typescript? I am currently facing an issue with the code. The error message says: Type 'Response' is missing the following properties from type 'myObj': userId, title, id I believe ...

Guide on dividing a URL string in Angular framework

Is there a way to include a value directly in the URL, like so: http://example.com/component/july2021 I need to extract july2021 from the component and separate it into "july" and "2021". How can I achieve this? ...

How can I set the default bindLabel for a dropdown in @ng-select/ng-select when the self change event occurs in Angular

I have a scenario where I need to set the default value to null in the ng-select. If the user selects an option from the dropdown first, then on the change event it should check if the Amount model is not null or blank. If the Amount model is blank, then ...

Implementing Batch File Uploads using Typescript

Is there a way to upload multiple files in TypeScript without using React or Angular, but by utilizing an interface and getter and setter in a class? So far I have this for single file upload: <input name="myfile" type="file" multi ...