Scott Leary Scott Leary - 8 months ago 8718
TypeScript Question

Typescript using constructor in a class won't allow for new keyword

I want to be able to new up my Menu Class but I cannot when using a constructor, why is this?

model = new Menu();


So that I can then set each property

this.model.AppGroupID = UserID;


component:

import { Menu } from '../../models/menu-model';

model = new Menu();

let UserID = params['UserID'];
this.model.AppGroupID = UserID;


ABOVE works fine when NOT using constructor

menu-model.ts file

export class Menu {
UserID: number;
AppID: number;
NavAppID: number;
AppGroupID: number;
SelectedCaseID: number;
SelectedRoleID: number;
}


so that above works fine
but why and how could i use a constructor for this? any benefit?

export class Menu {
constructor(
public UserID: number,
public AppID: number,
public NavAppID: number,
public AppGroupID: number,
public SelectedCaseID: number,
public SelectedRoleID: number
) { }

}

Answer Source

You are confusing a couple of different concepts I think.

This:

export class Menu {
   UserID: number;
   AppID: number;
   NavAppID: number;
   AppGroupID: number;
   SelectedCaseID: number;
   SelectedRoleID: number;
}

is basically the same as this:

export class Menu {

    constructor(
    ) { }

   UserID: number;
   AppID: number;
   NavAppID: number;
   AppGroupID: number;
   SelectedCaseID: number;
   SelectedRoleID: number;
}

i.e. if you don't specify a constructor it's basically the same as an empty constructor (I say basically as it's slightly different if you are extending a base class).

However this:

export class Menu {
    constructor(
        public UserID: number,
        public AppID: number,
        public NavAppID: number,
        public AppGroupID: number,
        public SelectedCaseID: number,
        public SelectedRoleID: number
    ) { }
}

Is different. If you define a constructor with parameters you need to provide arguments for those parameters when you call the constructor.

Because you declare the constructor parameters as "public" that also makes them properties of the class.

This is perhaps what is confusing? You don't need to create these properties in the constructor, that is just a convenient shorthand.

If don't want to specify the arguments in the constructor call don't make them parameters of the constructor, and instead declare them directly in the class body as in your first example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download