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

前端 未结 1 1980
北恋
北恋 2020-12-22 05:47

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

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

i         


        
相关标签:
1条回答
  • 2020-12-22 06:40

    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.

    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.

    0 讨论(0)
提交回复
热议问题