在Typescript中使用接口或类时 [英] When use a interface or class in Typescript

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

问题描述

我有一个简单的登录场景,要求用户在Typescript中输入电子邮件和密码。我需要创建某种类型以获得此强类型并将其发送到后端。

I have a simple scenario of a login that requires user's input a email and password in Typescript. I need to create some type to get this strong-typed and send it to the back-end.

应将其写为:

export interface UserLogin {
  email: string;
  password: string;
}
//OR
export class UserLogin {
  email: string;
  password: string;
}

又如何知道何时使用这些方案?

And how to know when is the scenario to use any of these?

推荐答案

最基本的说, class 本质上是对象工厂(也就是说,对象应该是什么样的然后被实现的蓝图),而接口是仅用于类型检查的结构。

At it's most basic, a class is essentially an object factory (ie. a blueprint of what an object is supposed to look like and then implemented), whereas an interface is a structure used solely for type-checking.

虽然可能具有初始化的属性和方法来帮助创建对象,但接口本质上定义了属性并输入对象可以拥有的类型。

While a class may have initialized properties and methods to help create objects, an interface essentially defines the properties and type an object can have.

在您描述的场景中,将使用界面设置UserLogin的类型。

In the scenario you described, one would use the interface to set the type for UserLogin.

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

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