'How can I destructure parameters on a function such that it can receive either the entire object or just a part of it?
For example, I have a vehicle object as
vehicle: {
make: { //say type Make
name: "acura",
model: "rdx"
},
user: { //say type User
name: "abc",
age: 30
},
addr: { //say type Address
number: 12,
street: 'xyz ave'
}
}
I want to write a function that can either receive the entire object or a partial object. So I did
function display({make}: {make?: Make} = {}, {user}: {user?: User} = {}, {addr}: {addr?: Address} = {}): void {
if(make) {
console.log(make.name);
}
if(user) {
console.log(user.name);
}
if(addr) {
console.log(addr.num);
}
}
display(vehicle); // Should display acura, abc, 12
display(vehicle.user); // Should display abc
Now, the above function works if I just pass the make or the entire vehicle object. Except of course it takes it as only the first parameter and the rest are undefined. How do I destructure the params properly to pass either a partial object or the entire object?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|