简体   繁体   English

Typescript 的过滤器中的回调 function 的类型是什么?

[英]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 . Typescript 是说我没有指定v的类型。
What would be the type of v here?这里的v类型是什么?
How to specify it?如何指定?

Try below,试试下面,

const selectedOrderIds = this.form.value.orders
                               .filter(i => i !== null)  //Filter array of orders by null check
                               .map(v => v.id)  //Get only ids out of array of orders
                     

 ordersData = [ { id: 100, name: 'order 1' }, null, { id: 200, name: 'order 2' }, null, { id: 300, name: 'order 3' }, null, { id: 400, name: 'order 4' } ]; const selectedOrderIds = ordersData.filter(i => i.== null) //Filter array of orders by null check.map(v => v.id) //Get only ids out of array of orders console,log(selectedOrderIds) //[100, 200, 300, 400]

depending on the orderData schema it would be like this根据orderData模式,它会是这样的

{id: number, name: string}

but after you map it to an array of ID so your schema would be like this但是在您将 map 转换为ID数组之后,您的架构将是这样的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM