Open In App

TypeScript Declaring this in a Function

Last Updated : 08 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript Declaring this in a Function, where ‘this’ in TypeScript refers to an object’s current instance in a function, granting access to its properties and methods. It’s essential to declare ‘this’ types for safety while using functions in TypeScript and properly declare the type of ‘this’.

Syntax:

const myFunction = (param1: number, param2: string) => {
// 'this' automatically captures
// the surrounding 'this' context
this.someMethod();
};

Parameters:

  • myFunction: This is the name of the function
  • param1, param2: These are the parameters that are passed to this function
  • number, string: These are types of param1, param2 respectively
  • this: This keyword will used to refer to the current instance of an object within a function

Example 1: In this example, we will see This TypeScript code showcases explicit ‘this’ type annotation within object methods, ensuring precise context adherence to defined interfaces, and enforcing strict typing for the ‘this’ keyword within objects.

Javascript




interface Course {
    course: string;
    id: string;
    changeCourse: () => void;
}
 
const gfg: Course = {
    course: 'Typescript',
    id: '768',
    changeCourse: function (this: Course) {
        this.course = 'React';
    },
};
 
console.log("Previous Course: " + gfg.course);
gfg.changeCourse();
console.log("New Course: " + gfg.course);


Output:

Previous Course: Typescript
New Course: React

Example 2: In this example, The code demonstrates a personalized greeting function utilizing explicit context binding through TypeScript’s this parameter, addressing users by name.

Javascript




function greet(this: { name: string }, greeting: string) {
    console.log(`${greeting}, ${this.name}!`);
}
 
const person = { name: 'GeeksforGeeks' };
greet.call(person, 'Hello');


Output:

Hello, GeeksforGeeks!

Example 3: In this example, we will see ‘this’ is not working in the arrow function. In this example,We have an arrow function assigned to hello that is trying to access object property using this, but it cannot access. However, since arrow functions don’t have their own this context, the this inside hello doesn’t reference the obj object.

Javascript




let obj = {
    username: ' GeeksforGeeks',
    hello: () => 'hello, ' + this.username
};
console.log(obj.hello());


Output:

Cannot read properties of undefined (reading 'username')

Conclusion : In this article we learnt that this keyword is used to refer to the current instance of an object within a function or method. It allows you to access properties and methods of the object from within the function.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads