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

How to Perform Runtime Type Checking for Interfaces in TypeScript?

DDD
DDDOriginal
2024-11-23 08:28:30260browse

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);
}

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);
}

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:
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