"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Perform Runtime Interface Type Checks in TypeScript?

How to Perform Runtime Interface Type Checks in TypeScript?

Published on 2024-12-23
Browse:827

How to Perform Runtime Interface Type Checks in TypeScript?

Interface Type Check in TypeScript

Within TypeScript, you may encounter a scenario where determining an object's compliance with a predefined interface at runtime is crucial. While class type checks leveraging the instanceof keyword are straightforward, applying it to interfaces presents a challenge.

Traditional approaches, such as relying on the instanceof operator, prove ineffective since interfaces lack representation as distinct types in compiled JavaScript. Instead, custom type guards offer a solution:

interface A {
    member: string;
}

function instanceOfA(object: any): object is A {
    return 'member' in object;
}

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

if (instanceOfA(a)) {
    alert(a.member);
}

This approach allows runtime verification of interface compliance without the need for the instanceof keyword.

In situations where multiple members must be checked, a discriminator property can be introduced. This approach requires managing your own discriminators and ensuring uniqueness to avoid conflicts:

interface A {
    discriminator: 'I-AM-A';
    member: string;
}

function instanceOfA(object: any): object is A {
    return object.discriminator === 'I-AM-A';
}

var a: any = { discriminator: 'I-AM-A', member: "foobar" };

if (instanceOfA(a)) {
    alert(a.member);
}

By employing custom type guards or discriminators, you can effectively perform interface type checks at runtime, enhancing the robustness of your TypeScript applications.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3