How to Check if an Object is Type of Interface in TypeScript?

Recently, while working in TypeScript, I got a requirement to check if an object is a type of interface. There are various methods to check. In this tutorial, I will explain how to check if an object conforms to an interface in TypeScript.

Check if an Object is Type of Interface in TypeScript

Interfaces in TypeScript define the structure that an object should adhere to. They specify the properties and methods that an object must have, enabling type checking and autocompletion. Here’s a simple example of an interface:

interface User {
  firstName: string;
  lastName: string;
  age: number;
  email: string;
}

In this example, any object conforming to the User interface must have firstName, lastName, age, and email properties with the specified types.

TypeScript’s static type checking helps catch errors at compile time, but there are scenarios where you need to ensure an object conforms to an interface at runtime. This is particularly useful when dealing with dynamic data, such as API responses or user inputs.

Now, let me show you how to check if an object is type of interface in TypeScript using different methods.

Check out Declare and Use TypeScript Interfaces with Nested Arrays of Objects

Method 1: Using Type Guards

One way to check if an object conforms to an interface is by using type guards. Type guards are functions that perform runtime checks to determine if an object meets specific criteria. Here’s an example:

interface User {
  firstName: string;
  lastName: string;
  age: number;
  email: string;
}
function isUser(obj: any): obj is User {
  return (
    typeof obj.firstName === 'string' &&
    typeof obj.lastName === 'string' &&
    typeof obj.age === 'number' &&
    typeof obj.email === 'string'
  );
}

const johnDoe = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30,
  email: 'john.doe@example.com'
};

if (isUser(johnDoe)) {
  console.log(`${johnDoe.firstName} ${johnDoe.lastName} is a valid user`);
} else {
  console.log('Invalid user object');
}

In this example, the isUser function checks if the johnDoe object conforms to the User interface by verifying the types of its properties.

Here is the exact output in the screenshot below:

Check if an Object is Type of Interface in TypeScript

Read How to Use TypeScript Interface Function Properties?

Method 2: Using Type Predicates

Type predicates are another way to perform runtime checks. They are similar to type guards but are more concise and readable. Here’s how you can use a type predicate:

interface User {
  firstName: string;
  lastName: string;
  age: number;
  email: string;
}
function isUser(obj: any): obj is User {
  return 'firstName' in obj && 'lastName' in obj && 'age' in obj && 'email' in obj;
}

const janeSmith = {
  firstName: 'Jane',
  lastName: 'Smith',
  age: 25,
  email: 'jane.smith@example.com'
};

if (isUser(janeSmith)) {
  console.log(`${janeSmith.firstName} ${janeSmith.lastName} is a valid user`);
} else {
  console.log('Invalid user object');
}

This method checks for the presence of required properties, making it a quick and efficient way to verify an object’s structure.

Read How to Define and Use TypeScript Interface Array of Objects?

Method 3: Using Runtime Validation Libraries

For more complex validation requirements, you can use runtime validation libraries such as io-ts or zod. These libraries provide robust solutions for validating objects against TypeScript interfaces or schemas.

Example with io-ts:

Here is an example.

import * as t from 'io-ts';

const User = t.type({
  firstName: t.string,
  lastName: t.string,
  age: t.number,
  email: t.string,
});

const michaelJohnson = {
  firstName: 'Michael',
  lastName: 'Johnson',
  age: 40,
  email: 'michael.johnson@example.com'
};

const validationResult = User.decode(michaelJohnson);

if (validationResult._tag === 'Right') {
  console.log(`${michaelJohnson.firstName} ${michaelJohnson.lastName} is a valid user`);
} else {
  console.log('Invalid user object');
}

Using io-ts, you can define a runtime schema that mirrors your TypeScript interface and validate objects against this schema.

Conclusion

In this tutorial, I explained how to check if an object is Type of Interface in TypeScript using different methods such as:

  • Using Type Guards
  • Using Type Predicates
  • Using Runtime Validation Libraries

Do let me know if you still have any questions.

You may also like: