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

How to Perform Runtime Type Checking for Interfaces in TypeScript?

DDD
Release: 2024-11-23 08:28:30
Original
369 people have browsed it

How to Perform Runtime Type Checking for Interfaces in TypeScript?

Interface Type Check with TypeScript

Question

How can one perform runtime type checking for interfaces in TypeScript, considering that JavaScript lacks the concept of interfaces?

Answer

While you cannot use instanceof with interfaces in TypeScript, you can create custom type guards to achieve the desired behavior:

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 cases where multiple members need to be checked, consider introducing 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

The above is the detailed content of How to Perform 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