Transpilation without interface

Based on the lesson, if we have previous classes with an interface but one of our classes doesn’t implement it, will it behave the same way anyways?

If so, does that mean I can do this every time to write fewer lines of code, or will it eventually not work?

Hi @Emilio_Parra !!
In TypeScript, the behavior you observed where a class that doesn’t explicitly implement an interface still works with that interface is due to TypeScript’s structural typing system. TypeScript checks whether a class “structurally” matches an interface based on the shape of the class (i.e., the presence of the required members) rather than relying on explicit implementations. This allows for flexibility but can also lead to unexpected behavior if not used carefully.

Here’s a summary of your questions:

  1. Behavior of Classes with Interfaces: When a class doesn’t explicitly implement an interface but has the required members (in terms of name and type), TypeScript considers it compatible with that interface. In your example, even though the Tulip class doesn’t implement the Greeter interface, it works because it has a greeting property with the correct type. This behavior is specific to TypeScript’s structural typing.

  2. Using This Approach: You can use this approach when it makes sense, but it should be used with caution. It can lead to confusion and unexpected behavior in more complex scenarios. It’s generally recommended to explicitly implement interfaces when you intend to adhere to a specific contract, as it makes your code more readable and understandable.

  3. Limitations: There are limitations to structural typing. For example, it doesn’t work with methods that have different parameter names, and it doesn’t account for private members. Also, relying solely on structural typing can make your code less self-documenting and harder to understand for other developers.

  4. Best Practices: It’s generally a best practice to explicitly implement interfaces when your classes are meant to adhere to a specific contract. This provides clarity and prevents unexpected issues.

In summary, while TypeScript’s structural typing can allow for more flexibility, it’s important to use it judiciously and consider the readability and maintainability of your code. Explicitly implementing interfaces is generally preferred when you want to clearly define and adhere to a contract.
Happy Learning :blush: