I am currently running this code on the typescriptlang.org (typescript playground)
After learning about the importance of types in TypeScript and how to use them in functions, I am having trouble adding specific types within this reduce method:
// Types for car
type Car = {
name:string,
age:number,
registered: boolean
};
// Reduce function to calculate the total number of registered cars.
function totalRegisteredCars(cars:Car[]) {
cars.reduce((acc:number , car:Car) => {
if(car.registered === true ) {
acc + 1;
}
},0);
}
var cars = [
{name:'vw' , age: 30, registered: true},
{name:'vw' , age: 32, registered: true},
{name:'Merc' , age: 25, registered: false},
{name:'bmw', age: 20, registered: false},
{name:'bmw' , age: 21, registered: true},
{name: 'ford', age: 31, registered: false},
{name: 'pinto', age: 43, registered: false},
{name: 'uno', age: 41, registered: true},
{name: 'ford', age: 30, registered: true},
{name: 'Mustang', age: 19, registered: false}
];
console.log(totalRegisteredCars(cars));
When testing this on https://www.typescriptlang.org/play, I encountered the following error:
Error message
No overload matches this call. Overload 1 of 3, '(callbackfn: (previousValue: Car, currentValue: Car, currentIndex: number, array: Car[]) => Car, initialValue: Car): Car', gave the following error.
Argument of type '(acc: number, car: Car) => void' is not assignable to parameter of type '(previousValue: Car, currentValue: Car, currentIndex: number, array: Car[]) => Car'. Types of parameters 'acc' and 'previousValue' are incompatible. Type 'Car' is not assignable to type 'number'.
Overload 2 of 3, '(callbackfn: (previousValue: number, currentValue: Car, currentIndex: number, array: Car[]) => number, initialValue: number): number', gave the following error. Argument of type '(acc: number, car: Car) => void' is not assignable to parameter of type '(previousValue: number, currentValue: Car, currentIndex: number, array: Car[]) => number'. Type 'void' is not assignable to type 'number'.
Question
Although I have specified my accumulator as a number and car as Car, why does the compiler show the above error?
I would like to understand why I cannot set a type to my accumulator as a number and how to properly assign types within a reduce function in the future.