TypeScript Declaring this in a Function
Last Updated :
24 Apr, 2025
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);