Check if a Method exists in a Class in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 28, 2022

banner

Check out my new book

Check if a Method exists in a Class in TypeScript #

Use the typeof operator to check if a method exists in a class, e.g. if (typeof myInstance.myMethod === 'function') {}. The typeof operator returns a string that indicates the type of the specific value and will return function if the method exists in the class.

index.ts
class Employee { constructor(public name: string, public salary: number) { this.name = name; this.salary = salary; } } interface Employee { getSalary?: () => number; } Employee.prototype.getSalary = function () { return this.salary; }; const emp1 = new Employee('James', 100); // ✅ Check for method's existence if (typeof emp1.getSalary === 'function') { console.log(emp1.getSalary()); // 👉️ 100 } else { console.log('method does NOT exist in the class'); }

Note that we used a question mark to set the getSalary method to optional in the Employee interface.

This means that the getSalary property can either have a value of undefined or be a method that returns a number.

We used the typeof operator to check if the getSalary property is a method.

index.ts
console.log(typeof function () {}); // 👉️ "function"

The typeof operator returns a string that indicates the type of the specific value.

This serves as a type guard in TypeScript.

index.ts
class Employee { constructor(public name: string, public salary: number) { this.name = name; this.salary = salary; } } interface Employee { getSalary?: () => number; } Employee.prototype.getSalary = function () { return this.salary; }; const emp1 = new Employee('James', 100); // 👇️ type is function or undefined emp1.getSalary; if (typeof emp1.getSalary === 'function') { // 👇️ type of emp1.getSalary is function console.log(emp1.getSalary()); // 👉️ 100 } else { console.log('method does NOT exist in the class'); }

The getSalary property is optional, so it can either have a value of undefined or be a function.

In our if statement we check if the specific property has a type of function, so TypeScript knows that it can't possibly be undefined in the if block.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.