I would like to dynamically assign multiple MyClass properties in TypeScript, so there is no need to write multiple lines of code to set class properties. I wrote the following code:
interface IMy
{
visible?: boolean;
text?: string;
}
class MyClass
{
element: JQuery;
assing(o: IMy): void
{
for (let [key, value] of Object.entries(o))
{
if (typeof value !== "undefined")
this[key] = value;
}
}
get visible(): boolean
{
return this.element.is(":visible");
}
set visible(visible: boolean)
{
this.element.css("display", visible ? "" : "none");
}
get text(): string
{
return this.element.html();
}
set text(text: string)
{
this.element.html(text);
}
}
let t = new MyClass();
t.assign({ visible: true });
t.assign({ text: "Something" });
t.assign({ text: "Something", visible: false });
but I have problems in the this[key] = value;error line :
The index signature of an object type is implicitly of type "any".
What do I need to change, or is my approach completely wrong?
It would also be a good solution to set the default properties in the constructor when the interface is a constructor parameter.
Edited:
I really liked the records, so I use this code:
interface Object
{
entries<T>(o: any): [string, T][];
entries(o: any): [string, any][];
}
if (!Object.entries)
{
Object.entries = function* entries(obj)
{
for (let key of Object.keys(obj))
{
yield [key, obj[key]];
}
};
}
Edited 2:
, .
, - .
interface IMy
{
prop1?: boolean;
prop2?: string;
prop3?: string;
prop4?: number;
}
class MyClass implements IMy
{
prop1: boolean = false;
prop2: string = "";
prop3: string = "Something";
prop4: number = 0;
constructor(properties: IMy)
{
this.assing(properties);
}
assing(o: IMy): void
{
let that = (<any>this);
for (let key in o)
{
if (o.hasOwnProperty(key))
{
let value = (<any>o)[key];
if (typeof value !== "undefined" && typeof that[key] !== "undefined")
that[key] = value;
}
}
}
}
let my1 = new MyClass({ prop1: true });
let my2 = new MyClass({ prop2: "SomeText", prop3: "Anything" });
let my3 = new MyClass({ prop4: 10 });
console.log(my1, my2, my3);