Home > Article > Web Front-end > How to Perform Runtime 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);
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); }
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!