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

查看:35
本文介绍了在 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?

推荐答案

在最基本的情况下,本质上是一个对象工厂(即什么的蓝图)一个对象应该看起来像然后实现),而接口是一种仅用于类型检查的结构.

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天全站免登陆