Home > front end >  How to use reduce to replace filter and map in typescript
How to use reduce to replace filter and map in typescript

Time:10-25

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

CodePudding user response:

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

CodePudding user response:

I try another way

interface employer { 
      name: string; 
      age: number; 
    } 
 
    const arr: employer[] = [{name:'Amy',age:18},{name:'Bob',age:20}]; 
 
    let data = arr.reduce((c:any, b:any) =>  b.age > 18 ? [...c, b] : c,[]) 
 
    console.log(arr)
  • Related