2

I'm trying to create a generic "mapping" method that can take an interface and JSON response then map the available keys to the interface. The issue I'm having is there seems no way to get the available properties of an interface without initializing them.

Is there a way to get the value of an interface without having to define it?

Joe Scotto
  • 10,936
  • 14
  • 66
  • 136

3 Answers3

0

Interfaces and other type information (with exceptions) are not available at runtime.

However, you can define a method that deserializes a JSON string into a given type. const myThing: IThing = JSON.parse(myJsonString); will cast it to the type IThing.

If you have a class Thing that implements IThing, you can use Object.keys to iterate over the keys of an instantiated Thing, and match the key indices together, like thing[key] = JSON.parse(...)[key]

schimmch
  • 3
  • 1
  • 2
0

interface and types in typescript are only checked when compiling (from ts to js). So, at runtime (which runs js), there is no information about interface.

But you can implement this with use of class and reflect-metadata and decorators, like class-transformer do.

Equal
  • 354
  • 3
  • 9
0

Simply switching my interfaces to a class was the solution. I am then able to create a blank instance and list out all available properties.

Joe Scotto
  • 10,936
  • 14
  • 66
  • 136