Issue
I have a class that looks as follows:
export class Lifter {
id: string;
name: string;
weightclass: number;
bestSnatch: number;
bestCJ: number;
bestTotal: number;
bio: string;
imageURL: string;
constructor(id: string, name: string, weightclass:number, bestSnatch:number, bestCJ:number, bestTotal:number, bio="Default biography text", imageURL = "https://upload.wikimedia.org/wikipedia/commons/a/a0/Arh-avatar.jpg") {
this.id = id;
this.name = name;
this.weightclass = weightclass;
this.bestSnatch = bestSnatch;
this.bestCJ = bestCJ;
this.bestTotal = bestTotal;
this.bio = bio;
this.imageURL = imageURL;
}
}
So in the constructor I pass default values for the properties "bio" and "imageURL". This is working fine when I create a new Lifter by:
new Lifter("1","Jesper",73,107,125,220),
the default values for Bio and ImageURL are successfully being added. Now to my question.
Is it possible to enter a value for the imageURL-property without passing a value to the bio-property?
I would in some cases want to add just an ImageURL, sometimes just a bio, sometimes both of them and sometimes none of them. I hope the question and the problem is somewhat clear.
The different calls I would want to be functioning is as follows:
new Lifter("1","Jesper",73,107,125,220), //None of the properties
new Lifter("2","Alfred",83,187,205,220,"Some Biography"), //Biography passed
new Lifter("3","Manfred",73,107,125,220,"https://www.w3schools.com/howto/img_avatar2.png"),//ImageURL passed
new Lifter("4","Sigfred",73,107,125,220,"Some other biography" ,"https://www.w3schools.com/howto/img_avatar2.png"),//Values for both properties passed
For clarification, it's just the 3rd case above that I have a problem with.
Solution
One way of doing this is through the object destructuring workaround for named parameters.
Your constructor destructures the object passed in as an argument:
constructor(id: string, name: string, weightclass:number, bestSnatch:number, bestCJ:number, bestTotal:number, {bio="Default bio", imageURL = "https://upload.wikimedia.org/wikipedia/commons/a/a0/Arh-avatar.jpg"} = {}) {
this.id = id;
this.name = name;
this.weightclass = weightclass;
this.bestSnatch = bestSnatch;
this.bestCJ = bestCJ;
this.bestTotal = bestTotal;
this.bio = bio;
this.imageURL = imageURL;
}
And you can call it like this by passing in appropriate objects:
new Lifter("1","Jesper",73,107,125,220)
new Lifter("2","Alfred",83,187,205,220,{bio: "Some Biography"})
new Lifter("3","Manfred",73,107,125,220,{imageURL: "https://www.w3schools.com/howto/img_avatar2.png"})
new Lifter("4","Sigfred",73,107,125,220,{bio: "Some other biography" , imageURL: "https://www.w3schools.com/howto/img_avatar2.png"})
Answered By - thabs
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.