Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate 'any' object against an interface in TypeScript at runtime [duplicate]

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.

like image 720
Trident D'Gao Avatar asked Oct 12 '12 22:10

Trident D'Gao


People also ask

How do you check if an object is an instance of an interface TypeScript?

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.

Can you extend multiple interfaces TypeScript?

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.

Can one interface extend another interface TypeScript?

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.

Is interface an object TypeScript?

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.


1 Answers

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.

like image 150
Brian Terlson Avatar answered Sep 16 '22 22:09

Brian Terlson