0

I have to generate a type at runtime, because the type can change. For the type - I know the name of each field(property) and their type. The data for this type is coming from REST api in form of a list of key/value pairs. When I receive this data, I need to map this to the right type/class/model so that I can later bind an array of this type to a grid.

I have looked at interface with Dynamic keys but the problem is I have to hard code the name of the key. I have also looked at the 'Record' type in typescript, but here also I to set the value for each key, I cannot use a variable - I need to hard code it - OK I can try to build the list of keys from my, but how will I assign a value to it without hardcoding.

//This is my function to generate an array of new type(lets say MYNEWTYPE) from An Array of Todo // A Todo has a list of TodoProperties inside it stored as a key/value pair public CreateNewArray(TodoList:Array):void{

TodoList.forEach((d) => {

  d.ToDoPropertiesDto.forEach((p)=>{

        //TodoProperties is alist of key/value pair (for example [{"Name":"Owner","Value":"MrJay"},{"Name":"Occupation","Value":"Engineer"}])

        // What I want is for example  if p.Name=Owner then assign p.value to MYNEWTYPE.Owner



  });

});

}

The expected result is an array of MYNEWTYPE where each field/property gets the value coming from the key/value pair. The problem is that someday they may want to add a new set of key/value pairs so I should create my new type from this list of key/value pairs

1 Answers1

0

Javascript is an untyped language. You can find explanation on this SO post: Is JavaScript an untyped language?.

Typing in Typescript is just there to help you out with semantics and sanity checking on your code at compile-time.

Once your code is compiled to Javascript and run, there are no typing information anymore. Anything will run as long as the key/value pair you are accessing exists.

So in your case, don't worry with typing as long as you know what you are doing: use type any. Obviously, you are on your own after that: it's up to you to not screw up and access non-existing fields or this will result in a runtime error. You will have no type system to point out any mistake you made in your code.

Qortex
  • 7,087
  • 3
  • 42
  • 59