What is the type of the callback function in filter of Typescript?

ordersData = [
  { id: 100, name: 'order 1' },
  { id: 200, name: 'order 2' },
  { id: 300, name: 'order 3' },
  { id: 400, name: 'order 4' }
  ];
  

constructor( private objHelloService: HelloServiceService, private formBuilder: FormBuilder ) 
  {  
    this.form = this.formBuilder.group({
      orders: new FormArray([])
      });
       
      this.addCheckboxes();
  }

  private addCheckboxes() 
  {
    this.ordersData.forEach((o, i) => {
                                        const control = new FormControl(i === 0); // if first item set to true, else false
                                        (this.form.controls.orders as FormArray).push(control);
                                      });
  }
  

submit() 
    {
      const selectedOrderIds = this.form.value.orders.map((v:string, i:number) => v ? this.form.value.orders[i].id : null).filter(v => v !== null);
      console.log(selectedOrderIds);
    }

Problem is here:

.filter(v => v !== null)

Typescript is saying that I have not specified the type of v.
What would be the type of v here?
How to specify it?

Answer

depending on the orderData schema it would be like this

{id: number, name: string}

but after you map it to an array of IDso your schema would be like this

.filter((v: number) => v !== null)

Leave a Reply

Your email address will not be published. Required fields are marked *