Warm tip: This article is reproduced from stackoverflow.com, please click
typescript

Requesting help to understand & how to initiate a typescript array of a class

发布于 2020-04-03 23:22:00

I broke it down to these two items MapComponent and a GeoPoint class. What am I missing here?

MapComponent

  • Are either of these the proper way to create an array of a class I've made so it is not undefined?
  • If not what is the correct way?
    // Initiate
    const response: Array<LatLngExpression> = []; // Seems to work
    const response: [LatLngExpression] = [];      // Msg: Type any[] is not assignable to type [any]
    // Add a value to the array
    response.push(geoPoint.getLatLng());

GeoPoint

export clas GeoPoint {
  private _id: string;
  private _value: LatLngExpression; // This is a leaflet.LatLngExpression
  private _selected: boolean = false;

  constructor (id: string, latLng:LatLngExpression, selected?:boolean) {
    this._id = id;
    this._value = latLng;
    if(selected){
      this._selected = selected;
    }
  }

  set()... // you get the idea
  get()... // you get the idea
}
Questioner
Elijah
Viewed
17
T.J. Crowder 2020-01-31 00:33

Your "Seems to work" one is correct:

const response: Array<LatLngExpression> = [];

You can also write it like this:

const response: LatLngExpression[] = [];

LatLngExpression[] is the type of response.

Ths is covered in the Handbook in the Basic Types > Array section.


In many cases you could also leave off the type entirely and allow TypeScript to infer it. But if you're starting with an empty array, that's actually more awkward than just providing the type annotation because you have to provide a type assertion instead. So it's probably not what you want, but just for completeness:

// I probably wouldn't do it this way
const response = [] as LatLngExpression[];