I have this class
export class dialogConfig {
title: String;
message?: String;
okText?: String;
withDecline?: false;
width?: Number;
height?: Number;
}
and I have this function
openDialog(config:dialogConfig){
...
});
I wanna call the function like this
openDialog({
title: 'viola'
}
The rest of the parameters that are not specified, I wanna set default values. How can I achieve this.
Things that should probably change about this question:
dialogConfigshould beDialogConfig, as it is conventional in TypeScript for named object types to start with an uppercase letter. Initial-lowercase identifiers usually signify variable names or possibly primitive types.I suspect you should be using an
interfaceinstead of aclass. The value{title: "viola"}is not actually an instance of any such class at runtime. You can use aclassas aninterface, which is whyopenDialog({title: "viola"})is not an error, but it's more straightforward to use aninterfacedirectly. Unless you are writingnew DialogConfig()orinstanceof DialogConfigyou don't needclass. And if you are writing those things you should be very careful with non-instance literals like{title: "viola"}.Numbershould benumberandStringshould bestring. It's almost always a mistake to use the uppercase versions of primitive data types.falseshould probably beboolean, unless you're saying thatwithDeclineshould, when specified, always befalse. That's possible, but I'm confused about how that would work with the intended use case of specifying default values when left out. If you ever wantwithDeclineto betrue, then you wantboolean.That gives us this:
That being said, here's how I'd assign default values:
Here I'm using an object called
defaultValues, and using object spread to create a new value with all the properties fromdefaultValueswhich is then overwritten with all the properties ofconfig. Assuming thatconfigdoesn't have any explicitly includedundefinedproperties, this will result in afilledInConfigvalue of typeRequired<DialogConfig>, the same asDialogConfigbut with all the properties required instead of having some of them as optional.If you don't want to use object spread there's also
Object.assign():Either way will result in the desired result:
Okay, hope that helps; good luck!
Playground link to code