How to Check the Type of an Object in Typescript ?
Last Updated :
01 Aug, 2024
When working with TypeScript, understanding how to check the type of an object is crucial for ensuring type safety and maintaining code integrity. TypeScript, being a statically typed superset of JavaScript, provides several approaches to accomplish this task as listed below.
Using the typeof Operator
This operator returns a string indicating the type of the operand. We can operate this with the objects to check their type in TypeScript.
Syntax:
typeof variableName
Example: The below example demonstrates how to use the typeof operator to determine the type of a variable.
JavaScript
interface myInterface {
name: string,
est: number
}
let x: myInterface = {
name: "GFG",
est: 2009
};
console.log(typeof x);
Output:
object
Using the instanceof Operator
This operator checks whether an object is an instance of a particular class or constructor. We can operate it by defining the testing object name before it and the class name after it.
Syntax:
objectName instanceof ClassName
Example: The below example illustrates the usage of the instanceof operator to check if an object is an instance of a class.
JavaScript
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
let person = new Person("John");
console.log(person instanceof Person);
Output:
true
Using Type Guards
Type guards are functions that return a boolean indicating whether an object is of a specific type.
Syntax:
function isType(obj: any): obj is TypeName {
// Type checking logic
}
Example: The below example demonstrates the implementation of a type guard function to check if an object satisfies a specific interface.
JavaScript
interface Animal {
name: string;
}
function isAnimal(obj: any):
obj is Animal {
return obj &&
typeof obj.name === 'string';
}
let animal = {
name: "Dog",
sound: "Bark"
};
if (isAnimal(animal)) {
console.log(animal.name);
}
Output:
Dog
Using User-Defined Type Predicates
User-defined type predicates in TypeScript provide a way to define custom logic to check whether a variable is of a specific type. By using the as keyword in the return type of a function, you can create a type predicate that helps TypeScript infer the type of an object.
Example: The below example demonstrates how to create and use a user-defined type predicate to check if an object is of a specific type.
JavaScript
interface Dog {
breed: string;
bark: () => void;
}
interface Cat {
breed: string;
meow: () => void;
}
function isDog(obj: any): obj is Dog {
return obj && typeof obj.bark === 'function';
}
const pet1: Dog = { breed: 'Labrador', bark: () => console.log('Woof!') };
const pet2: Cat = { breed: 'Siamese', meow: () => console.log('Meow!') };
console.log(isDog(pet1));
console.log(isDog(pet2));
Output:
true
false
Similar Reads
How to check interface type in TypeScript ? Typescript is a pure object-oriented programming language that consists of classes, interfaces, inheritance, etc. It is strict and it statically typed like Java. Interfaces are used to define contacts in typescript. In general, it defines the specifications of an entity. Below is an example of an in
2 min read
How to Check Types in Typescript? Checking types in TypeScript involves methods like typeof for primitive types, instanceof for class instances, and custom type guards for complex type validation. These techniques help ensure variables are correctly typed, improving code safety, and readability, and preventing runtime errors.Here ar
3 min read
How to Declare Specific Type of Keys in an Object in TypeScript ? In TypeScript, object definitions can include specific key-value types using index signatures. You can declare specific types of keys in an object by using different methods as listed below:Table of ContentUsing Mapped TypesUsing InterfaceUsing Inline Mapped Types with typeUsing Record Utility TypeU
3 min read
How to Check if an Object is Empty in TypeScript ? In TypeScript, it's common to encounter scenarios where you need to determine if an object is empty or not. An empty object typically means it contains no properties or all its properties are either undefined or null. Below are the methods to check if an object is empty or not in TypeScript: Table o
3 min read
How to check the type of a variable or object in JavaScript ? In this article, How to Check the Type of a Variable or Object in JavaScript? In JavaScript, the typeof operator is used to determine the typeof an object or variable. JavaScript, on the other hand, is a dynamically typed (or weakly typed) language. This indicates that a variable can have any type o
2 min read