Borislav Hadzhiev
Mon Feb 28 2022·2 min read
Photo by Marc Babin
To check if an object has a method in TypeScript:
typeof
to check if accessing the method on the object returns a value
with a function
type.typeof
operator returns true
, the method exists.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.
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.
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.
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.