← Back
typescript

Typescript annotations to reduce function

Using reduce with Typescript can be tricky. Given that random example:

const blocked = seatStatuses.reduce(
(result, seatStatus) => (seatStatus.isBlocked ? ++result : result),
0
);

In the above example, TS can infer 0 is a constant (instead of a number). And it emits a type exception (in strict mode).

There are two solutions:

Add annotation to the function #

const blocked = seats.reduce<number>(
(result, seatStatus) => (seatStatus.isBlocked ? ++result : result),
0
);

Add annotation to the accumulator #

const blocked = seats.reduce(
(result, seatStatus) => (seatStatus.isBlocked ? ++result : result),
0 as number
);

More info: https://stackoverflow.com/questions/57379778/typescript-type-for-reduce

🖖