There are a few pieces that you need to solve this puzzle.
First of all, we need to add types allowing us to set any property on the class. We can do that as follows:
class CreateObjects {
propertyTest: KeyValue = {key: 'Example', value: 'Object'};
[key: string]: any;
When we define our method, we want to take all of the arguments as an array. We can use ...args, which creates an array called args with each of the arguments passed to the array:
methodTest(...args: any[]) { }
I didn't use the name "arguments", because this is a reserved keyword in JavaScript. It could be used to solve this problem, but I think it's more complicated when working with TypeScript.
Finally, we need to iterate over each argument, and set a property on the class. We can do that like this:
for (let i = 0; i < args.length; i = i + 1) {
this['Example' + i] = {key: 'Example', value: args[i]};
}
You'll hopefully recognise the for loop. We're using "this" to access a property on the class. One caveat of this approach is that if the method is called from outside of the class, the "this" binding will be different, and the properties might be set on something else.
Finally, here's everything put together, with some test code at the bottom to see it working:
interface KeyValue {
key: string;
value: string;
}
class CreateObjects {
//example of how im tyring to make the objects look
propertyTest: KeyValue = {key: 'Example', value: 'Object'};
[dynamicProperty: string]: any;
//function that creates objects like above but does so dynamically with unique and iterative property names
methodTest(...args: any[]) {
for (let i = 0; i < args.length; i = i + 1) {
this['Example' + i] = {key: 'Example', value: args[i]};
}
}
}
const example = new CreateObjects();
example.methodTest("a", 1);
console.log(example.Example0);
console.log(example.Example1);
I wouldn't say I'm particularly fond of setting properties on a class like this. You may want to think if you can change your design to improve the safety you get from TypeScript. For example, could you instead have a single property that stores an array of these objects?