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

How to Perform Runtime Interface Type Checking in TypeScript?

Susan Sarandon
Release: 2024-11-16 16:52:03
Original
720 people have browsed it

How to Perform Runtime Interface Type Checking in TypeScript?

Interface Type Checking in TypeScript

In TypeScript, a common dilemma arises when attempting to verify if a variable of type any adheres to a specified interface at runtime. Consider the following code:

interface A {
    member: string;
}

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

if (a instanceof A) alert(a.member);
Copy after login

Here, the TypeScript playground generates an error on the final line, claiming that the name A is undefined in the current scope. However, this is incorrect as A is clearly defined. To resolve this issue, it's important to understand that interfaces have no representation in the generated JavaScript, rendering runtime type checks impossible.

This dilemma stems from JavaScript's dynamic nature, where interfaces have no defined existence. Consequently, the question arises: is there a way to type-check for interfaces in TypeScript?

The playground's autocompletion indeed reveals a method called implements, leaving us wondering how to utilize it. Here's where custom type guards come into play:

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

With this approach, you can type-check an interface without the need for instanceof. However, for more complex cases, consider using discriminators to manage your own discriminators and ensure no duplicates occur.

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

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template