初始数据的TypeScript可以使用接口类型或类类型哪种方法更好? [英] TypeScript for initial data can use interface type or class type Which way is better?

查看:141
本文介绍了初始数据的TypeScript可以使用接口类型或类类型哪种方法更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在TypeScript中获取初始数据可以使用接口类型或类类型
哪种方法更好?

In TypeScript for initial data can use interface type or class type
Which way is better?

export interface Item{
    text: string,
    value: number
}

itemModel: ItemComboBox = {
    value:'value1',
    text: 'text1'
  };

班级:

export class Item{
  constructor(
     public text: string,
     public value: string) { }
}
itemModel= new Item("text1", "value1"); 

推荐答案

如果您需要创建一个自定义对象的实例,同时又能获得类型检查的好处,例如参数,返回类型或泛型-一个类说得通.如果您不创建实例-我们可以使用接口,那么它们的好处就在于它不生成任何源代码,而是允许我们在某种程度上虚拟"地对我们的代码进行类型检查.

If you need to create an instance of perhaps a custom object, whilst getting the benefits of type-checking things such as arguments, return types or generics - a class makes sense. If you’re not creating instances - we have interfaces at our disposal, and their benefit comes from not generating any source code, yet allowing us to somewhat "virtually" type-check our code.

由于接口和类都定义了对象的结构,并且在某些情况下可以互换使用,所以值得注意的是,如果我们需要在各个类之间共享结构定义,则可以在接口中定义该结构,然后让每个类都实现该接口!然后,每个类都必须声明或实现接口的每个属性.这就是TypeScript的强大功能,而且还非常灵活.我们拥有全面的面向对象设计和通用的类型检查.

Since both an interface and a class define the structure of an object and can be used interchangeably in some cases, it’s worth noting that if we need to share structural definition amongst various classes, we can define that structure in an interface and then have each class implement that interface! Each class then will have to declare or implement each property of the interface. That’s the power of TypeScript, and it’s also super flexible. We have comprehensive object-oriented design paired with versatile type-checking.

因此,对于定义简单数据类型,我认为接口是更好的解决方案.

so for defining simple data types i think interfaces are better solution.

这篇关于初始数据的TypeScript可以使用接口类型或类类型哪种方法更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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