I am working on the UI of an app using typescript. At the same time others work on providing me data. We agreed on the data contract however the process is error prone and I keep getting invalid data objects from the server. So my question is can I somehow validate dynamic objects (at run time) using some of my interfaces defined in typescript?
This question was asked in 2012, thus it cannot be a duplicate of Check if an object implements an interface at runtime with TypeScript asked in 2015.
Use a user-defined type guard to check if an object implements an interface in TypeScript. The user-defined type guard consists of a function, which checks if the passed in object contains specific properties and returns a type predicate.
You can extend from as many interfaces as necessary by separating the interfaces with a comma. You are not required to add any new members to the final interface and can use the extends keyword to simply combine interfaces.
However, we can override protected methods in sub-classes as in the following code: In TypeScript, interfaces can extend each other just like classes. This lets us copy the members of one interface to another and gives us more flexibility in how we use our interfaces.
TypeScript Interface Define Objects Only In TypeScript, type aliases can define composite types such as objects and unions as well as primitive types such as numbers and strings; interface, however, can only define objects. Interface is useful in typing objects written for object-oriented programs.
As it stands, TypeScript interfaces are purely compile time entities so there is no way to do any sort of runtime validation let alone even knowing what interfaces existed at compile time. Thus, the answer would seem to be one of:
You could use JSON-schema as your runtime representation, as many validators exist on Github. A TypeScript interface --> JSON Schema converter is something I hope someone makes at some point, but as far as I'm aware doesn't exist as yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With