chuckd
chuckd

Reputation: 14600

How to initialize child objects when using object in Typescript

Still learning Typescript and I have this object

export class Marker {
    position: {
        lat: number,
        lng: number,
    };
    label: {
        color: string,
        text: string,
    };
    title: string;
    options: {
        animation: any,
    };
}

and in my code where I use it I do so like this, but marker.position is undefined

for (const ybEvent of this.Events) {
  const marker = new Marker();
  marker.title = ybEvent.name;
  marker.position.lat = ybEvent.latitude;
  marker.position.lng = ybEvent.longitude;
  marker.label.color = 'blue';
  marker.label.text = ybEvent.description;
  marker.options.animation = google.maps.Animation.BOUNCE;
  this.markers.push(marker);
}

What is the best way to initialize position, label, and options in this object?

Upvotes: 0

Views: 1293

Answers (1)

distante
distante

Reputation: 7005

First of all I would recommend you to use Typescript on strict mode.

When you use typescript with strict mode, an error will be show if a class member does not have any initialization:

enter image description here

I would also define the structure of each object (also inside objects).

interface Position {
    lat: number,
    lng: number,
}

interface Label {
        color: string,
        text: string,
};
interface Options {
        animation: any,
}

And if your Marker object does not require any internal logic, then I would also set it as an interface:

interface Marker {
    position: Position;
    label: Label;
    title: string;
    options: Options;
}

And your initialization could be something like:

for (const ybEvent of this.Events) {
    const position: Position = {
        lat: ybEvent.latitude,
        lng: ybEvent.longitude,
    };

    const label: Label = {
        color: 'blue',
        text: ybEvent.description,
    }

    const options: Options = {
        animation: google.maps.Animation.BOUNCE
    }

    const marker: Marker = {
        position,
        label,
        options,
    }

    this.markers.push(marker);
}

Or without intermediate objects:

for (const ybEvent of this.Events) {

    const marker: Marker = {
        position: {
            lat: ybEvent.latitude,
            lng: ybEvent.longitude,
        },
        label: {
            color: 'blue',
            text: ybEvent.description,
        },
        options: {
            animation: google.maps.Animation.BOUNCE
        }
    }

    this.markers.push(marker);
}

Keep in mind, the idea of Typescript is to have type safety. If you initialize a object in this way myObject = {} it does not have any type information.

Upvotes: 1

Related Questions