superman1971
superman1971

Reputation: 209

Instantiating a Class in 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?

Upvotes: 10

Views: 56601

Answers (3)

Gollm
Gollm

Reputation: 130

In my case, i only needed a check to specific classes. I used 'constructor.name', which crashed on production mode.

I used it in a switch-statement with error on default

switch (constructorInput.constructor.name) {
        case 'A':
            // do something
            break;
        case 'B':
            // do something
            break;
        default:
            throw new Error(constructorInput.constructor.name + ' is no valid Type');
    }

So, i already could change it to instanceof

if (constructorInput instanceof A) {
        // do something
    } else if (constructorInput instanceof B) {
        // do something
    } else {
        throw new Error('no valid Type');
    }

This is working at production and development.

Upvotes: 0

mk.
mk.

Reputation: 11740

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", ...}

Upvotes: 12

billc.cn
billc.cn

Reputation: 7317

TypeScript behaves similarly to the underlying JavaScript (and most other languages) in terms of object instantiation: all fields are initialised to undefined unless you override it with a value.

Also, there's no way to instantiate an interface. Instead you have to supply an object matching the signature. If you don't want to supply all the fields at the beginning, you can mark the fields in the interface with ? so they become optional, then you can do

export class ChartOptions {
    options: myOptions = {};
...

Upvotes: 0

Related Questions