Creating model classes in TypeScript

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.

Leave a Comment