Correctly Extend a Class: Constructor

586
1
09-23-2021 02:16 PM
Alexandre-Notos
New Contributor III

I'm looking for guidance with how to properly extend a class with respect to its constructor. All of this is in typescript. I'm extending the Graphic class. Normally the graphics class take a GraphicProperties object. I'm my class I had new properties.  I would like to change the constructor from

 

constructor(properties?: any) { ... }

 

to

 

    constructor(properties?: SegmentProperties) { ... }

 

Also, is it possible to define the type of properties without initializing them in the constructor?

My full code is below:

 

import Graphic from "@arcgis/core/Graphic";
import Polyline from "@arcgis/core/geometry/Polyline";
import LineSymbol3D from "@arcgis/core/symbols/LineSymbol3D";
import LineSymbol3DLayer from "@arcgis/core/symbols/LineSymbol3DLayer";

import { subclass, property } from "@arcgis/core/core/accessorSupport/decorators";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import Point from "@arcgis/core/geometry/Point";

import * as watchUtils from "@arcgis/core/core/watchUtils";

@subclass("esri.core.Graphic.SegmentGraphic")
export class SegmentGraphic extends Graphic{

    @property()
    startPoint: Graphic;

    @property()
    endPoint: Graphic;

    @property({
        readOnly: true
      })
      get length(): number {
        return 10;
      }

    constructor(properties?: any) {
        
        super(properties);
        this.startPoint = properties.startPoint;
        this.endPoint = properties.endPoint;

        this.updatePolyline()

        this.symbol = new LineSymbol3D({
            symbolLayers: [
                new LineSymbol3DLayer({
                    size: 5,
                    material: {
                        color: "red"
                    }
                })
            ]
        });

        this.registerWatchUtil(this.startPoint);
        this.registerWatchUtil(this.endPoint);
    }

    private updatePolyline() {
        let polyline = new Polyline({spatialReference: this.startPoint.geometry.spatialReference});
            polyline.addPath([this.startPoint.geometry as Point, this.endPoint.geometry as Point]);
            this.geometry = polyline 
    }

    private registerWatchUtil(point: Graphic){
        watchUtils.when(point, "geometry", (geometry) => {
            this.updatePolyline()
        })
    }
}

 

0 Kudos
1 Reply
ReneRubalcava
Frequent Contributor

I would probably do it like this.

class SegmentGraphic extends Graphic {
  // so that all props are not required
  constructor(params: Partial<SegmentGraphic>) {}
}

 

0 Kudos