在 TypeScript 中创建模型类 [英] Creating model classes in TypeScript

查看:56
本文介绍了在 TypeScript 中创建模型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 TypeScript 的新手,我有 C# 和 JavaScript 背景.我正在尝试创建一种方法,允许我创建类似于我们在 C# 中可以做的类模型.

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

这是我尝试过的:

export class DonutChartModel {
    dimension: number;
    innerRadius: number;
    backgroundClass: string;
    backgroundOpacity: number;
}

我希望这会生成一个公开声明属性的 JavaScript 模型,但这只会生成一个没有声明属性的函数 DonutChartModel.

I expected this to generate a JavaScript model that exposes the properties declared, but this generates only a function DonutChartModel with no properties declared.

查看文档后,我注意到为了公开属性,我必须添加一个构造函数并从那里初始化属性.虽然这可能有效,但在每个模型可能有 20 个或更多属性的情况下无济于事,因为在我看来,初始化可能看起来很笨拙,而且还会稍微降低可读性.

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

TypeScript 中是否有任何选项可以执行此操作?

Is there any option in TypeScript to do this?

推荐答案

看起来您试图完成的是在模型上强制执行结构.虽然在 C# 中使用类来实现这一点很有意义,但在 TypeScript 中最好的方法是创建一个 type 或一个 interface.

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
};

何时使用:

接口可以从/通过类进行扩展,最适合在定义属性时使用.

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';

关于类型的优秀资源可以在这里找到,或者作为TypeScript:接口与类型的答案.

An excellent resource on types can be found here, or as answers to TypeScript: Interfaces vs Types.

这篇关于在 TypeScript 中创建模型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆