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?
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).
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.
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", ...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With