sun1211
sun1211

Reputation: 1578

How to use reduce to replace filter and map in typescript

I have a simple example like

    interface employer {
      name: string;
      age: number;
    }

    const arr: employer[] = [{name:'Amy',age:18},{name:'Bob',age:20}];

    let data = arr.reduce((c, b) =>  b.age > 18 ? [...c, b] : c,[])

    console.log(data)

I just want to filer arr array and return the age of the person is higher than 18 for example But I get errors

No overload matches this call.
  Overload 1 of 3, '(callbackfn: (previousValue: employer, currentValue: employer, currentIndex: number, array: employer[]) => employer, initialValue: employer): employer', gave the following error.
    Type 'employer[]' is missing the following properties from type 'employer': name, age
  Overload 2 of 3, '(callbackfn: (previousValue: never[], currentValue: employer, currentIndex: number, array: employer[]) => never[], initialValue: never[]): never[]', gave the following error.
    Type 'employer[]' is not assignable to type 'never[]'.
      Type 'employer' is not assignable to type 'never'.

For this b.age > 18 ? [...c, b] : c I think it worked for javascript How can we fix it? Thanks

Upvotes: 1

Views: 4137

Answers (2)

sun1211
sun1211

Reputation: 1578

I try another way

interface employer {
  name: string;
  age: number;
}

const arr: employer[] = [{name:'Amy',age:18},{name:'Bob',age:20}];

let data: employer[] = arr.reduce((c: employer[], b: employer) =>  b.age > 18 ? [...c, b] : c,[])

console.log(data)

Upvotes: -1

Georgios Kampitakis
Georgios Kampitakis

Reputation: 475

In order to fix this error, you need to add type on the reduce function. You can do this by calling

let data = arr.reduce<employer[]>((c, b) =>  b.age > 18 ? [...c, b] : c,[])

also, this is valid

let data = arr.reduce((c, b) =>  b.age > 18 ? [...c, b] : c,[] as employer[])

but I think the first one looks better.

You can find a working example in this playground

Upvotes: 3

Related Questions