Why do we have to write return
keyword within rawApiData.map callback arrow function in this case?
protected assembleLCodeDealers(rawApiData): DealerLossCodeDealer[] {
if (rawApiData) {
return rawApiData.map(p => {
return {
code: p.code,
id: p.id,
name: p.name
} as DealerLossCodeDealer;
});
} else {
return [];
}
}
CodePudding user response:
You may be confused by the arrow function shorthand syntax with 1 returned expression, which indeed does not need an explicit return
.
But if you use curly braces, it opens a code block for multiple expressions, not an object to be returned.
Simply wrap the curly braces of the object to be returned with parentheses, to avoid them from being interpreted as a code block:
rawApiData.map(p => ({
code: p.code,
id: p.id,
name: p.name
}) as DealerLossCodeDealer)
See the advanced syntax