Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

Typescript : setter and inheritance on interfaces

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...