简体   繁体   中英

typescript : Argument of type 'any[]' is not assignable to parameter of type '[]'.ts(2345)

export class ServiceAreaComponent implements OnInit, OnDestroy {
  _clickedPoint = [];

  this.serviceArea.getToken().subscribe((d) => {
    this.isLoading = true;
    this.getServiceArea(this._clickedPoint);
  })
}

getServiceArea(pointArray: [], driveTimeList ? : any) {}

I've declared one class property called _clickedPoint = [] as an array. And the typescript takes it as Array<any> . At same time I've created a method inside the class to accept clicked point and i declared a method parameter called pointArray:[] same as like _clickedPoint . Bu this time typescript takes this array without any type assigned . I just wanted to know why typescript is not assigning type any to method parameters

_clickedPoint = []; is an initialization (with an empty array), of a member without a type. Typescript will infer the type of _clickedPoint to be an array, of type any (so any[] , or never[] depending on compiler settings, but you seem to be in the former case)

pointArray: [] is a parameter of type empty tulpe ( [] ). Tuples at runtime are arrays but typescript will check that the length of the tuple and the items in the tuple are of the correct type (read more about tuples here )

Typescript will infer types if none are specified, such as when you don't specify the type of the member, but will take the exact type you spelled out in a type annotation without adding anything to it, such as when you specified it for the parameter. In this case it is a bit confusing since the empty array literal [] has a different type than the empty tuple type (also [] but used as a type annotation)

What you really want is for pointArray to be an array type:

export class ServiceAreaComponent {
  _clickedPoint = [];
  test() {
    this.getServiceArea(this._clickedPoint);
  }
  getServiceArea(pointArray: any[], driveTimeList?: any) {
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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