angulartypescriptangular5angular6

Why should I be using interfaces (models) in Typescript / Angular?


The way I see it, defining objects with models seems to make them rigid and less change tolerant, making it easier to break an application in the future and adding lines of code for no gain. For instance I could have a get method that returns a video object from an API and program it as Any or as a defined model.

/model/video.ts

export interface Video {
// my code
 }

/pages/videos.ts

getAllVideos(): Promise<Video> {
// my code
}

vs.

/pages/videos.ts

getAllVideos(): Promise<Any> {
// my code
}

The way I see it. Less lines of code, less complexity, less files and less rigidity is a good thing. Why even have models defined?


Solution

  • ...making it easier to break an application in the future...

    This is exactly the opposite of what happens when you introduce interfaces to JS with Typescript.

    Let's say you have a function that accepts objects with a certain shape, like so

    function giveMeStuff(obj) {
      return obj.foo.toLowerCase();
    }
    

    In this case, we have no way to make sure that when we call giveMeStuff we are actually passing an object which has foo property, which also needs to be a string.

    If a new developer (or yourself, a few weeks later) comes along and calls giveMeStuff(12), the code will break at runtime.


    Instead, this is what happens when you have an interface.

    function giveMeStuff(obj: IObjectWithFoo): string {
      return obj.foo.toLowerCase();
    }
    
    interface IObjectWithFoo {
      foo: string;
    }
    

    now, when you try to call giveMeStuff(12) the compiler will warn you that you can't do that, because the function is expecting a different kind of argument.