Issue
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?
Solution
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.
Answered By - Brocco
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.