I have the current code running on typescriptlang.org (typescript playground)
I have read up on the importance of types in typeScript and how to use them in functions. However i'm struggling with adding the following types in this reduce method:
// Types for car
type Car = {
name:string,
age:number,
registered: boolean
};
// Reduce function to hopefully get the total number of cars that are registered.
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 having this in the https://www.typescriptlang.org/play i get 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
I could be missing a simple step, but the compiler complains about how my accumulator which i have typed as a number and car which i have typed as Car seems to give me the error logged above.
I just want to know why I cannot set a type to my accumulator as a number. and how should I set types inside a reduce function in future?
0
which is not of type car? (genuine suggestion, not an answer) – evolutionxbox