How to check if a variable implements an interface in TypeScript?

How can I check if a variable implements an interface in TypeScript at runtime? I am trying to determine if a variable of type any implements a specific interface, but I encounter issues with using instanceof with interfaces. For example:

interface A { member: string; }

var a: any = { member: “foobar” };

if (a instanceof A) alert(a.member);

In TypeScript, instanceof does not work with interfaces, as they do not have a runtime representation. The TypeScript playground shows an error, “The name A does not exist in the current scope.” How can I perform a type check for interfaces at runtime? Additionally, I noticed TypeScript offers a method called implements. How can I use typescript instanceof interface for this purpose?

Hello HeenaKhan,

To check if a variable implements an interface in TypeScript at runtime, you can use the following approaches :

  1. Type Guard Function: You can create a type guard function that manually checks if the object conforms to the expected structure of the interface:

interface A { member: string; }

function isA(obj: any): obj is A { return typeof obj === ‘object’ && obj !== null && ‘member’ in obj; }

const a: any = { member: “foobar” };

if (isA(a)) { alert(a.member); // Now TypeScript knows a is of type A }

In this method, isA is a user-defined type guard function that checks if the object has the required properties of the interface.