Home > Web Front-end > JS Tutorial > How to Achieve Runtime Type Checking for Interfaces in TypeScript?

How to Achieve Runtime Type Checking for Interfaces in TypeScript?

DDD
Release: 2024-11-17 13:24:01
Original
700 people have browsed it

How to Achieve Runtime Type Checking for Interfaces in TypeScript?

Interface Type Check in TypeScript

In TypeScript, interfaces define contracts that objects can follow, but they don't enforce their implementation at runtime. This means that using instanceof to check if a variable implements an interface will fail.

To achieve runtime type checking for interfaces, you can use custom type guards. These are functions that take an object as an argument and return a boolean indicating whether it implements the desired interface:

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);
}
Copy after login

For interfaces with a large number of members, you can add a discriminator property:

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);
}
Copy after login

This allows for efficient type checking without having to check all members individually.

The above is the detailed content of How to Achieve Runtime Type Checking for Interfaces in TypeScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template