Setting dynamic properties using a key from a private collection in TypeScript
Running this at http://www.typescriptlang.org/Playground ...
interface TestObj {
name:String;
}
class Test {
test;
private myCollection:TestObj[] = [];
private anyCollection:any[] = [];
constructor() {
var obj:any = {};
var refObj = {name:'prop'};
obj[refObj.name] = "This works!";
var collection:any[] = [];
collection.push(refObj);
this.test[collection[0].name] = "This works!";
this.myCollection.push(refObj);
obj[this.anyCollection[0].name] = "This works!?";
this.myCollection.push(refObj);
obj[this.myCollection[0].name] = "What the deuce!?! this.myCollection[0].name is supposed to be a string! Am I not?";
var newRefObj:TestObj = { name: 'prop' };
this.myCollection.push(newRefObj);
obj[this.myCollection[1].name] = "This doesn't work either.";
}
}
I get this in the last part of the instruction.
An index expression argument must be of type 'string', 'number', 'symbol, or 'any'.
(property) Test.myCollection: TestObj[]
I guess I may have difficulty understanding the "private" properties. I've done crazy research, but I'm seriously having a hard time understanding how the geek speaks. I can't seem to find anyone else who has this problem, so I'm guessing it's something like a noob.
Ideally, I would rather show an error if I tried to use myCollection outside of the Test class.
source to share
Primitive string type string
, not string
. Change the interface accordingly:
interface TestObj {
name: string;
}
string
for a String object, and string
for a primitive type. For example:
var obj: any = {};
var strObj = new String("test"); // typed as String
var str = "test"; // typed as string
obj[strObj] = "test"; // error you were seeing
obj[str] = "test"; // ok
source to share