I have two typescript interfaces, one of which inherits from the other (in the final application I will have several levels of inheritance).
I want to have a method to modify the properties of all types of objects that inherit from my main class. Be careful, in this method, the name of the property is not necessarily identical to a property name declared in my interface.
Also, when entering my modifier, I don't know what type of object I am passing initially. If I don't do a single modifier for all objects that inherit from a class, I'm afraid I might have to duplicate code.
I thought to make a map or I associate a key which would be the property and in value of a function which would be my modifier, but that does not seem to be able to be done (typescript control on the types of objects).
Sample code :
interface PositionnedItem {
x: number;
y: number;
}
interface BoxedItem extends PositionnedItem {
tickness: number;
}
function setProperty<T extends PositionnedItem>(item: T, property: string, value: number): void {
if(property === 'raz') {
item.x = 0;
item.y = 0;
item.tickness = 0;
} else if(property === 'all') {
item.x = value;
item.y = value;
item.tickness = value;
} else {
item[property] = value;
}
}
question from:
https://stackoverflow.com/questions/66049976/typescript-setter-and-inheritance-on-interfaces 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…