I'd say the function does something like this:
interface Options {
userId: number;
}
interface ReturnItem {
userName: string;
}
const getUserProfile = async (options: Options): Promise<ReturnItem> => {
// make some request with the id
const response = await axios.get(`/look/up/my/user/${options.userId}`);
return response.data;
}
The destructuring is based off of the types defined in the function, so instead of getting an object back, you're just pulling the item out of the returned object as the types define that's what you can expect to receive.
Instead of doing the following:
const myId = 1;
const myResult = await getUserProfile({userId: myId});
console.log(myResult.userName);
you can do:
const userId = 1;
const {userName} = await getUserProfile({userId});
console.log(userName);
Another example:
const myReturnData = {
userName: 'Bjork'
};
userName can now be accessed in the following ways:
console.log(myReturnData.userName);
or
const {userName} = myReturnData;
console.log(userName);
Destructuring is taking those values in your object and assigning them to variables.
A bit further..
const myReturnData = {
userName: 'Bjork',
coolnessFactor: 10000
};
const {userName, coolnessFactor} = myReturnData;
console.log('My User is: ', userName);
console.log('and my Coolnessfactor is: ', coolnessFactor);
getUserProfileis a function which returns a promise. The({ userId })part is creating an object with the property shorthand. The promise is being awaited and thenuserNameis being assigned/destructured from the returned value.const user = await getUserProfile({ userId }); const userName = user.userName