lundi 21 novembre 2022

Setting object property by string name

Very new to typescript and am trying to port some C# code. I need to be able to set an instances properties by property string name.

In C# I do this with reflection, but how can I do this in typescript?

The following is a simplified example:

class BaseClazz {
  baseA?: string;
  baseB?: string;
}

class DerivedClazz extends BaseClazz {
  derived1?: number;
  derived2?: number;
  array1?: number[];
  array2?: number[];
}

I want a function that can set the various properties by their string name:

function assign(clazz: BaseClass, propertyName: string, value: any) {
  ...
}

In theory I can call it as follows and each of the 4 properties would be set:

test:BaseClazz = new DerivedClazz();
assign(test, "baseA", "a");
assign(test, "baseB", "b");
assign(test, "derived1", 1);
assign(test, "derived2", 2);
assign(test, "array1", [1, 2, 3, 4]);
assign(test, "array2", [5, 6, 7, 8]);





Aucun commentaire:

Enregistrer un commentaire