何时在 Angular 项目中使用类或接口? [英] When to use Class or Interface in Angular project?

查看:22
本文介绍了何时在 Angular 项目中使用类或接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天来到这里是因为我有一个问题,就像标题所说的,关于Angular 中的类和接口.

I’m here today because I’ve a question about, like the title said, about classes and interfaces in Angular.

从我的角度来看,我理解这一点:

From my Point of View, I understand this:

接口在 Typescript 中用于执行类型检查,它们存在于直到转译并消失在生产中.此外接口不能用于实例化.

Interfaces are used in Typescript to perform type-checking, they are here until the transpilation and disappear in the production. Also Interface cannot be used to instantiate.

来自 ES6 的类也用于类型检查,但它们在编译后保留并生成代码 在生产中.此外,它们用于实例化.

Classes came from ES6 are also used for type-checking, but they stay after transpilation and generate code in the production. Also, they are used to instantiate.

所以,基本上,如果我们在生产中不需要它们,如果我们只需要类型检查,Interface 很有用.相反,如果我们在生产中需要它们,尤其是在实例化时,Class 就在这里.

So, basically, Interface is useful if we don’t need them in production, if we only need to type-check. On the opposite, Class are here if we need them in production, particularly for the instantiation.

我是对的还是我错过了关于类和界面的一些东西?

推荐答案

你说得对.当您只需要类型检查时,接口很棒,而当您不仅需要类型检查,而且需要一些方法或需要一些其他逻辑时,类也很棒.

You're correct. Interfaces are great when you only need the type checking whereas classes are great when you not only want the type checking, but you need some methods or require some other logic.

就我个人而言,我总是从只使用一个接口开始,一旦我需要一些方法,我就会添加一个类并继承该接口.我还要补充一点,我无论您是否使用类,都希望总是有一个接口.这允许您传递/注入接口,而不必多次重新实例化类.

Personally, I always start with just using an interface, and once I need some methods, I'll add a class and inherit the interface. I would also add that I prefer to always have an interface whether you're using a class or not. This allows you to pass around/inject the interface instead of having to re-instantiate class multiple times.

这是一个典型模式的例子,如果我需要一些方法(这意味着我需要一个class)

Here is an example of a typical pattern I would follow if I need some methods (which means I need a class)

interface IPerson {
    firstName: string;
    lastName: string;
    age: number;
    getFullName(): string;
}
class Person implements IPerson {
    public firstName: string;
    public lastName: string;
    public age: number;
    constructor(firstName: string, lastName: string, age: number) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
    getFullName(): string {
        return `${this.firstName} ${this.lastName}`
    }
}

const person: IPerson = new Person('John', 'Doe', 44);

我永远不会在任何地方注入或需要导入 Person 除非我真的需要更新"一个新人.我总是可以注入 IPerson 代替,只要作为类传入的内容,接口将允许我调用所有类方法并根据需要访问属性.

I would never inject or need to import Person anywhere unless I actually needed to 'new up' a new person. I can always inject IPerson instead and so long as what was passed in as the class, the interface will allow me call all the class methods and access the properties as I wish.

然而,有时我不需要方法,但我需要一个数据契约(或者只是想抑制 TypeScript 被激怒我没有告诉它一切是什么):

However, sometimes I don't need methods, but I need a data contract (or just want to suppress TypeScript from being pissed off I'm not telling it what everything is):

interface IPerson {
    firstName: string;
    lastName: string;
    age: number;
}

const person: IPerson = <IPerson>{
    firstName: 'John',
    lastName: 'Doe',
    age: 44
};

这样做仍然为您提供了一种方法来动态创建一个符合界面的变量.但是,当您这样做时没有任何方法(因此您会丢失 getFullName 函数并且必须手动运行该函数)

Doing it this way still gives you a way to create a variable on the fly that adheres to the interface. However, there are no methods when you do it this way (so you lose your getFullName function and would have to run that manually)

总的来说,我发现自己在结构化 json 的 http 返回上使用接口.我真的不需要在前端对他们做任何更多的事情,因为后端已经为我完成了繁重的工作.因此,为每个返回值创建一个类可能有点矫枉过正,但有些人更喜欢这样.

Overall, I find myself using interfaces on http returns that are structured json. I don't really need to do anything more to them on the front end as the backend has done the heavy lifting for me already. So, creating a class for each one of those returns may be overkill, but some people prefer it that way.

要提出的另一件事是,创建所有这些模型非常耗时.不过还是有回报的.在我的一个项目中,我使用 npm 模块根据我的 c# 模型自动生成 TypeScript 接口.这节省了大量的打字时间,并认为它非常酷(https://www.npmjs.com/package/csharp-models-to-typescript)

One other thing to bring up is that creating all these models is extremely time consuming. It pays off though. In one of my projects, I used an npm module to automatically generate TypeScript interfaces based off my c# models. That saved a ton of typing and thought it was pretty cool (https://www.npmjs.com/package/csharp-models-to-typescript)

另一种流行的解决方案是使用 Swagger Codegen.您可以大摇大摆"您的后端,并让 swagger 代码生成器为您生成模型和服务.它很光滑.这是一个示例存储库 使用 Angular 和 C# 作为后端.

One other popular solution is to use Swagger Codegen. You can 'swaggerize' your backend and have swagger codegen just generate your models and services for you. It's pretty slick. Here's an example repo using Angular and C# as the backend.

总的来说,这确实是您的偏好.请记住,如果您需要方法和额外的层来构建给定的模型,类是最好的.如果您只需要类型而不关心其他花哨的语法糖",只需使用接口即可.正如您提到的,界面在生产中消失了,所以这当然是一个加分项.

In general, it's really your preference. Just keep in mind, if you need methods and extra layers to build out a given model, a class is best. If you just need types and don't care about the rest of the fancy 'syntactical sugar' just use an interface. As you mentioned, interfaces disappear in production so it's certainly a plus.

https://jsfiddle.net/mswilson4040/3vznkbq0/7/

这篇关于何时在 Angular 项目中使用类或接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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