Validate 'any' object against an interface in TypeScript at runtime

Trident D'Gao picture Trident D'Gao · Oct 13, 2012 · Viewed 8.5k times · Source

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.

Answer

Brian Terlson picture Brian Terlson · Oct 13, 2012

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:

  1. Write some tool to convert TypeScript interfaces to some runtime object representation that you can use to validate your objects, or:
  2. Duplicate your TypeScript interfaces as some runtime object representation

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.