Categories
TypeScript Answers

How to check if an object implements an interface at runtime with TypeScript?

Spread the love

Sometimes, we want to check if an object implements an interface at runtime with TypeScript.

In this article, we’ll look at how to check if an object implements an interface at runtime with TypeScript.

How to check if an object implements an interface at runtime with TypeScript?

To check if an object implements an interface at runtime with TypeScript, we can create our own function.

For instance, we write

interface Test {
  prop: number;
}

function isTest(arg: any): arg is Test {
  return typeof arg?.prop === "number";
}

to define the isTest function that returns the arg is Test type.

This lets the TypeScript compiler know that it’s a type guard function.

Then we check if arg.prop is a number with typeof in it and return the result.

Conclusion

To check if an object implements an interface at runtime with TypeScript, we can create our own function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *