Skip to content Skip to sidebar Skip to footer

Why Should I Use Interfaces As Data Types In Angular If There Are Classes Allready?

I recently watched tutorial of my teacher, and he show us this code: And he also said products array which is type of any [] IS NOT USING BENEFITS OF STRONGLY TYPE which is featur

Solution 1:

Check this text writen by James Henry maybe that will clarify you this issue. In short: Unlike classes, interfaces are completely removed during compilation and so they will not add any unnecessary bloat to our final JavaScript code.


Solution 2:

Think of interfaces as a blueprint for your object — a brief set of instructions that guarantees that a certain set of fields / methods will be available on objects tagged with that interface. They provide you with a means of taking advantage of strong typing while keeping your code as lightweight as possible. As mentioned, the interface is removed and compile time because it doesn’t actually have any programmatic implications — it’s strictly to make the code less error-prone and easier to work with for you and whoever else.

If you need to specify implementation details, such as getter / setter / constructor logic or methods, that’s when you would use a class. In fact, if the logic for the calculateDiscount() method in your example is expected to remain the same across all Products, it’s possible that a class could make more sense in this case.


Solution 3:

Classes can work as interfaces in TypeScript. Interfaces cannot work as classes. One of them can be chosen based on the principle of parsimony.

Things like

class SomeProductClass implements ProductClass {...}

and

const plainProduct: ProductClass = {...};

happen often.

However, when a class is defined, it's expected that it or its descendant will be instantiated. If it won't, this would be misleading, because this is what interfaces are for.

It's common in Angular to define abstract class that won't be instantiated, but that's because abstract classes can be used as both interfaces and dependency injection tokens.


Post a Comment for "Why Should I Use Interfaces As Data Types In Angular If There Are Classes Allready?"