78

Hi I am new to TypeScript and I come from both a C# and JavaScript background. I am trying to create a way that allows me to create class models similar to what we can do in C#.

Here is what I have tried:

export class DonutChartModel {
    dimension: number;
    innerRadius: number;
    backgroundClass: string;
    backgroundOpacity: number;
}

I expected this to generate a JavaScript model that exposes the properties declared, but this generates only a function DonutChartModel with no properties declared.

After looking at the docs I noticed that in order to expose the properties I have to add a constructor and initialize the properties from there. While this may work, it does not help situations where you may have 20 or more properties per model, as the initialization might look pretty clunky, in my opinion, and it also reduces readability a bit.

I am hoping there is a way to do something like this without passing constructor params:

var model = new DonutChartModel();
model.dimension = 5
model.innerRadius = 20
....

Is there any option in TypeScript to do this?

James Skemp
  • 8,018
  • 9
  • 64
  • 107
aleczandru
  • 5,319
  • 15
  • 62
  • 112

4 Answers4

128

What it appears you are attempting to accomplish is to enforce a structure on a model. While it makes sense to use a class in C# to accomplish this, in TypeScript the best approach is to create either a type or an interface.

Here are examples of both (reduced properties for brevity)

Type

type DonutChartModel = {
    dimension: number;
    innerRadius: number;
};
var donut: DonutChartModel = {
    dimension: 1,
    innerRadius: 2
};

Interface

interface IDonutChartModel {
    dimension: number;
    innerRadius: number;
}
var donut: IDonutChartModel = {
    dimension: 1,
    innerRadius: 2
};

When to Use:

Interfaces can be extended from/by classes and are best for when you are defining properties.

Types can be combined and should be used more for non-composite properties. A good example would be to use types for something like this:

type Direction = 'up' | 'down' | 'left' | 'right';

An excellent resource on types can be found here, or as answers to TypeScript: Interfaces vs Types.

James Skemp
  • 8,018
  • 9
  • 64
  • 107
Brocco
  • 62,737
  • 12
  • 70
  • 76
  • Digging into the SO question linked at the bottom of this questions, it sounds like the tl;dr is that you should use interfaces generally. It sounds like the only currently outstanding difference between the two is that you can define the same interface twice, and they get merged together automatically. Types cannot, and would error in this case. – Aaron Krauss Nov 12 '20 at 21:39
36

Yes, you can do it.

Step 1: Create your model using “Classes”. While TypeScript has interfaces that can provide this functionality, the Angular team recommends just using a bare ES6 class with strongly typed instance variables. ES6 classes allow you to (optionally) build out functionality around your models and also doesn't require you to be locked into a TypeScript specific feature. For these reasons, it's advisable to use classes for creating models.

export class DonutChartModel {

//Fields 
dimension: Number
innerRadius: Number
backgroundClass: Number
backgroundOpacity: Number
myPropertyToSet: String 

constructor (dimension: Number, innerRadius: Number){
   this.dimension = dimension
   this.innerRadius = innerRadius
}}

Step 2: Import it into your component. This will give you the added benefit of reuse the data model in multiple places.

import { DonutChartModel } from '../../models/donut-chart-model;

Step 3: Set one of the properties values:

export class MenuSelectionPage {

 myDonuts: DonutChartModel[] = [];

 constructor(public navCtrl: NavController, public navParams: NavParams) {
  this.FillLocalData()
  this.myDonuts[this.myDonuts.length - 1].myPropertyToSet = "I am your father" 
 } 

//Aux Methods
FillLocalData() {
let dimensions = [8.32, 5, 17];
let defaultInnerRadius = 2;
for (let i = 0; i < dimensions.length; i++) {
  let donut = new DonutChartModel (dimensions[i], defaultInnerRadius * i)
  this.myDonuts.push(donut)
}}}

Step 4 (Optional): Use it in html.

 ...
 <ion-list>
    <button ion-item *ngFor="let donut of myDonuts">
    {{donut.myPropertyToSet}}
     </button>
 </ion-list>
 ...

Note: This code has been tested in ionic 3

Ore4444
  • 9,119
  • 2
  • 23
  • 29
Ariel Antonio Fundora
  • 1,330
  • 15
  • 20
24

Giving the fields default values should do what you're looking for.

export class DonutChartModel {
    dimension: number = 0;
    innerRadius: number = 0;
    backgroundClass: string = "";
    backgroundOpacity: number = 0;
}
Joe Clay
  • 33,401
  • 4
  • 85
  • 85
1

You are looking for the shorthand known as Parameter Properties:

export class DonutChartModel {
  constructor(
    dimension: number,
    innerRadius: number,
    backgroundClass: string,
    backgroundOpacity: number
  ) {}
}

Credit to Robert Komaromi and the author of this article

DonCarleone
  • 544
  • 11
  • 20