Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating a Class in TypeScript

Tags:

typescript

I have the following class structure

module ChartingServices {

export class ChartOptions {
    options: myOptions;
    title: string;
}

export interface myOptions {
    colors: string[];
    legend: myLegend;
    type: string;
}

export interface myLegend{
    enabled: boolean;
    labelFormatter: string;
}
}

and I create an instance of it in the usual way:-

var chartOptions = new ChartingServices.ChartOptions();

I can set the property chartOptions.title with no problem at all.

However, I cannot get to the property chartOptions.myOptions.type and get an error about not being able to read property 'type' of undefined.

Bearing in mind I have loads of classes, do I need to create an instance of each one to set / read properties. What can I do to get the code to work?

like image 592
superman1971 Avatar asked Dec 16 '15 16:12

superman1971


People also ask

What is declare class in TypeScript?

declare class is for when you want to describe an existing class (usually a TypeScript class, but not always) that is going to be externally present (for example, you have two . ts files that compile to two . js files and both are included via script tags in a webpage).

Do TypeScript classes need a constructor?

Classes in TypeScript do not require you to explicitly write a constructor. However if you are extending a base class you will need to create a constructor to call super() at a minimum.


1 Answers

The first problem is that .myOptions does not exist on chartOptions - you want options. You should capitalize all of your types: MyOptions, MyLegend, so that you do not confuse them with property names.

The second problem is that although you instantiate a new ChartOptions:

var chartOptions = new ChartOptions();

...its options property isn't actually set to anything, and is therefore undefined. You need to set it either using a statement right after instantiation:

chartOptions.options = {type: "foo", ...other non-optional properties here}

Or in the constructor of ChartOptions, or via:

options: MyOptions = {type: "foo", ...}
like image 99
mk. Avatar answered Sep 28 '22 09:09

mk.