Hi I am new to typescritpt 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 tryed:
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 these 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 an initialize the properties from there. While this may work it does not help situations where you may have 20 or more propeties per model the initialization might look preety cluncky 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
....
So is there any option in typescript to do this?
Giving the fields default values should do what you're looking for.
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 aninterface
.Here are examples of both (reduced properties for brevity)
Type
Interface
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:
An excellent resource on types can be found here.
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.
Step 2: Import it into your component. This will give you the added benefit of reuse the data model in multiple places.
Step 3: Set one of the properties values:
Step 4 (Optional): Use it in html.
Note: This code has been tested in ionic 3