79660461

Date: 2025-06-10 12:58:36
Score: 1
Natty:
Report link

.reduce() is a generic method and the right way to do it is to pass resulting type into generic definition (.reduce<number[]>()) (TS playground)

const data = [{Key: 56}, {Key: undefined}, {}, {Key: 44}]

const keys = data.reduce<number[]>((prev, curr) => {
  if (curr.Key) {
    return [...prev, curr.Key];
  } else return prev;
}, []);

Generic-based approach is more preferable because it will do type-checking of what is really returned in the callback, and it will warn if type mismatches

Reasons:
  • Has code block (-0.5):
  • Starts with a question (0.5): is a
  • Low reputation (1):
Posted by: Octopi