Whats the difference between using a class and interface?

后端 未结 2 629
情歌与酒
情歌与酒 2020-11-30 13:14

What is the difference between doing this

export class Comment {
  likes: string;
  comment: string;

  constructor(likes: string, comment: string){
    this         


        
2条回答
  •  我在风中等你
    2020-11-30 13:31

    As in most other OOP languages: For classes you can create instances (via their constructor), while you cannot create instances of interfaces.

    In other words: If you just return deserialized JSON, then it makes sense to use the interface to avoid confusion. Lets assume you add some method foo to your Comment class. If your register method is declared to return a Comment then you might assume that you can call foo on the return value of register. But this wont work since what register effectively returns is just deserialzed JSON without your implementation of foo on the Comment class. More specifically, it is NOT an instance of your Comment class. Of course, you could also accidentally declare the foo method in your CommentInterface and it still wouldn't work, but then there would be no actual code for the foo method that is just not being executed, making it easier to reason about the root cause of your call to foo not working.

    Additionally think about it on a semantic level: Declaring to return an interface gurantees that everything that is declared on the interface is present on the returned value. Declaring to return a class instance gurantees that you... well... return a class instance, which is not what you are doing, since you are returning deserialized Json.

提交回复
热议问题