I am new to typescript and typing overall. I am using the generics for dynamic properties. This is not my actual code, but I am facing the same issue.
class Units<T> {
constructor(units: T) {
Object.assign(this, units);
}
}
const myUnits = {
archers: 5,
samurais: 10,
berserks: 3
};
const army = new Units(myUnits);
army.archers;
Error on the last line.
Property 'archers' does not exist on type 'Units<{ archers: number; samurais: number; berserks: number; }>'.
What am I doing wrong, maybe there is better approach? If I can do that on JS why Typescript restricting?
Units<T>means that you will have aUnitsinstance that uses that genericTyou pass into the constructor. It does not mean thatUnitswill inherit any properties offT. Think of it like this - you have, say aPersonclass which has anameproperty, butArray<Person>doesn't havenameproperty - it doesn't inherit anything from the generic it uses.Tproperties will be inUnitstoo?A<T>whereTdetermines what fields and methods instances ofAhave is simply put strange. This sort of situation is typically more suited to composition, if anything. I suppose there is some TypeScript way to say that a method that does something to the effect of<t> method(T arg): ? extends Tbut it's still odd. Perhaps you should look at mixins as that's effectively what you do, rather than a generic class.