Creating model classes in TypeScript

后端 未结 3 1413
别跟我提以往
别跟我提以往 2021-02-01 12:48

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#.

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 13:12

    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.

提交回复
热议问题