我想动态地将多个属性分配给TypeScript中的MyClass,因此不需要编写多行代码来设置类属性。我写了下面的代码:如何在TypeScript中动态地赋值类属性
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 });
//instead t.visible = true;
//or
t.assign({ text: "Something" });
//instead t.text = "something";
//or
t.assign({ text: "Something", visible: false });
//instead t.visible = true;
// t.text = "something";
,但是,我有错误的行this[key] = value;
问题:
Index signature of object type implicitly has an 'any' type.
我需要改变还是我的做法是完全错误的?
当interface是构造函数参数时,在构造函数中设置默认属性也是一个很好的解决方案。
编辑:
关于条目我真的很喜欢他们,所以我用这个代码:
//extensions.d.ts
interface Object
{
entries<T>(o: any): [string, T][];
entries(o: any): [string, any][];
}
//exntesion.js !!note js not ts
if (!Object.entries)
{
Object.entries = function* entries(obj)
{
for (let key of Object.keys(obj))
{
yield [key, obj[key]];
}
};
}
编辑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" });
//I set prop2 and prop3
let my3 = new MyClass({ prop4: 10 });
//I set prop4 (fourth parameter)
console.log(my1, my2, my3);