Borislav Hadzhiev
Last updated: Feb 28, 2022
Check out my new book
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.
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.
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.
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.
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.