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#.
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 DonutChartModel = {
dimension: number;
innerRadius: number;
};
var donut: DonutChartModel = {
dimension: 1,
innerRadius: 2
};
interface IDonutChartModel {
dimension: number;
innerRadius: number;
}
var donut: IDonutChartModel = {
dimension: 1,
innerRadius: 2
};
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.