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.

Hello Heena,

Hello everyone! :blush:

When dealing with Type Assertion and Type Guards in TypeScript, it’s essential to ensure that an object conforms to a specific interface. Here’s a clear approach to achieve this using a combination of type assertions and type guards:

interface A {
    member: string;
}

const a: any = { member: "foobar" };

function assertIsA(obj: any): asserts obj is A {
    if (typeof obj !== 'object' || obj === null || !('member' in obj)) {
        throw new Error("Object does not implement interface A");
    }
}

try {
    assertIsA(a);
    alert(a.member); // TypeScript now understands `a` is of type `A`
} catch (e) {
    console.error(e.message);
}

In this example, the assertIsA function checks whether the object matches the structure of interface A. If it doesn’t, an error is thrown, providing a mechanism for runtime type checking. This approach ensures that TypeScript recognizes the type of a as A once the assertion passes, enhancing type safety in your code.

I hope you find this useful! Let me know if you have any questions or further insights. Happy coding!