Unlocking Typescript's power: Mastering Advanced Object Types with Interfaces and Types

ยท

2 min read

Introduction

TypeScript, a statically typed superset of JavaScript, empowers developers to define custom types, adding a layer of predictability to their code. In this article, we'll explore advanced object types in TypeScript, focusing on the use of interfaces and types.

Advanced Object Types

We can define types in various ways, including using the type keyword (covered in a future article). Another method involves using the interface keyword.

From the code above, we observe a slight syntax difference between types and interfaces. Notably, the interface do not require an (=) sign before the typed object.

But significant difference is that an interface can only be used to type objects, whereas type can extend its functionality to cover objects, primitives, and more. Despite this versatility, interfaces play a crucial role in object-oriented programs.

Interface and Classes

The interface keyword proves invaluable for adding types to classes in TypeScript, especially in object-oriented programming. This synergy arises from the ability to apply a type to an object or class using the implements keyword.

In the example above, an interface named Page is applied to a class named Book using the implements keyword. The Page interface specifies a .finish() method, and since it's applied to the Book class, Book must include a matching .finish() method. Additionally, Book can have its own methods and properties that are not present in the interface.

What to take Home

The implements keyword and interfaces empower developers to create types that match various class patterns, making them valuable tools in object-oriented programs.

ย