Home > Article > Web Front-end > How to Perform Runtime Type Checking for Interfaces in TypeScript?
How can one perform runtime type checking for interfaces in TypeScript, considering that JavaScript lacks the concept of interfaces?
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!