.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