Home >Web Front-end >JS Tutorial >How to Achieve Runtime Type Checking for Interfaces in TypeScript?
Interface Type Check in TypeScript
In TypeScript, interfaces define contracts that objects can follow, but they don't enforce their implementation at runtime. This means that using instanceof to check if a variable implements an interface will fail.
To achieve runtime type checking for interfaces, you can use custom type guards. These are functions that take an object as an argument and return a boolean indicating whether it implements the desired interface:
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 interfaces with a large number of members, you can add 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); }
This allows for efficient type checking without having to check all members individually.
The above is the detailed content of How to Achieve Runtime Type Checking for Interfaces in TypeScript?. For more information, please follow other related articles on the PHP Chinese website!