- Published on
TypeScript: How to use instanceof, typeof and in
Table of Contents
The instanceof operator
The instanceof
operator is used to determine whether an object is an instance of a particular class or interface. It is often used in TypeScript to check whether an object conforms to a certain interface or has a particular class as its prototype.
ts-instanceof.ts
interface Member {
fullName: string
subscriptionID?: number
}
const member: Member = {
fullName: 'John Smith',
subscriptionID: 12345
};
if (member instanceof Member) {
console.log('This is a member object');
} else {
console.log('This is not a member object');
}
The typeof operator
The typeof
operator is used to determine the type of a variable or expression. It is often used in TypeScript to check whether a variable or expression has a particular type.
ts-typeof.ts
interface Member {
fullName: string
subscriptionID?: number
}
const member: Member = {
fullName: 'John Smith',
subscriptionID: 12345
};
if (typeof member === 'object' && member !== null) {
console.log('This is an object');
if ('subscriptionID' in member) {
console.log('This is a member object');
}
}
Here, we first check if the value is an object and not null, since typeof null returns "object". And we check if the subscriptionID
property is in the object, indicating that it satisfies the Member interface. Here alternatively we could use the instanceof.