0

I have an object like below:

var objContainer = {};
objContainer.string1 = "some string";
objContainer.string2 = "some string";
....
objContainer.stringN = "some string";

I want to create a type for objContainer variable in TypeScript.The point is, the variable count and names are unknown. So, I want to introduce a logic like "for each variable inside objContainer's type class will be string type, disregarding its name". Is there any way to accomplish that? Pseudo-code example is:

interface ExampleInterface{
   objContainer:ExampleClass;
}
class ExampleClass{
   {All Variables}:string;
}
Deniz Beker
  • 1,984
  • 1
  • 18
  • 22

1 Answers1

2

Probably you want to use interface like this:

interface Map 
{
    [K: string]: string;
}

let dict: Map = {};
dict["string1"] = "some string";
let val = dict["string1"];

Hope this helps.

Amid
  • 21,508
  • 5
  • 57
  • 54
  • It worked. Thanks a lot. However, this solution needs a conversion of typing. I had to change all codes objContainer.string1 = "some string"; to objContainer["string1"] = "some string";. Then it worked. Just to know, would it be possible to do it without changing the structure of existing implementation? – Deniz Beker Jan 22 '16 at 10:22
  • I am afraid - no. If you want type assertion and do not know your properties in advance. Otherwise you can always fall back by casting your objContainer to "any" like this: let o = objContainer. And from that access its properties in the original unsafe manner: o.string1 = '111'. – Amid Jan 22 '16 at 10:27