Check if an Object has a Method in TypeScript

avatar

Borislav Hadzhiev

Mon Feb 28 20222 min read

banner

Photo by Marc Babin

Check if an Object has a Method in TypeScript #

To check if an object has a method in TypeScript:

  1. Mark the specific method as an optional key in the object's type.
  2. Use typeof to check if accessing the method on the object returns a value with a function type.
  3. If the typeof operator returns true, the method exists.
index.ts
interface Employee { name: string; salary: number; getSalary?: () => number; } const obj: Employee = { name: 'Alice', salary: 500, }; if (typeof obj.getSalary === 'function') { console.log(obj.getSalary()); } else { console.log('getSalary method does not exist on object'); }

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

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
interface Employee { name: string; salary: number; getSalary?: () => number; } const obj: Employee = { name: 'Alice', salary: 500, }; // 👇️ type is function or undefined obj.getSalary; if (typeof obj.getSalary === 'function') { // 👇️ type of obj.getSalary is function here console.log(obj.getSalary()); } else { console.log('getSalary method does not exist on object'); }

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.

Here are some more examples of using the typeof operator.

index.js
console.log(typeof {}); // 👉️ "object" console.log(typeof []); // 👉️ "object" console.log(typeof null); // 👉️ "object" console.log(typeof (() => {})); // 👉️ "function" console.log(typeof ''); // 👉️ "string" console.log(typeof 0); // 👉️ "number" console.log(typeof NaN); // 👉️ "number" console.log(typeof undefined); // 👉️ "undefined"

Note that the return value from the operator is always wrapped in a string.

Use the search field on my Home Page to filter through my more than 1,000 articles.