代码之家  ›  专栏  ›  技术社区  ›  edjm

请求帮助以了解&如何启动类的typescript数组

  •  1
  • edjm  · 技术社区  · 5 年前

    我错过了什么?

    地图组件

    • 如果不是,正确的方法是什么?
        // 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());
    

    地质点

    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
    }
    
    2 回复  |  直到 5 年前
        1
  •  1
  •   T.J. Crowder    5 年前

    你的“似乎起作用”是正确的:

    const response: Array<LatLngExpression> = [];
    

    你也可以这样写:

    const response: LatLngExpression[] = [];
    

    LatLngExpression[] response .

    本手册在 Basic Types > Array section


    在许多情况下,您还可以完全关闭类型并允许TypeScript推断它。但是,如果您从一个空数组开始,这实际上比仅仅提供类型注释更尴尬,因为您必须提供一个类型断言。所以这可能不是你想要的,只是为了完整:

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