Chuck's Academy

Basic TypeScript

Interfaces and Types in TypeScript

In TypeScript, interfaces and types are powerful tools that allow you to define clear and precise data structures. These structures help make the code more maintainable and easier to understand, as they explicitly define what types of values can be expected by functions, classes, and other elements.

Defining Interfaces

An interface in TypeScript is a contract that defines the shape that an object should have. It does not specify implementations, just the structure. Let's see a basic example:

typescript
"Here we define an interface called User that describes an object with three properties: id of type number, username of type string, and email which is optional. Then we create a user object that follows this interface."

Extending Interfaces

TypeScript allows interfaces to be extended, which means an interface can inherit properties from another and add its own. This is useful when you want to create more complex structures based on simpler ones.

typescript
"In this example, the Employee interface extends the Person interface, meaning that Employee inherits the firstName and lastName properties, and adds a new property called jobTitle. We create an employee object that follows this structure."

Defining Types

In addition to interfaces, TypeScript allows you to define custom types using the type keyword. Types can be used to create more flexible structures or aliases for complex types.

typescript
"In this example, we define a type called Point that describes an object with two numeric properties, x and y. Then we create an object named point that follows this structure."

Type Aliases

Type aliases are useful to simplify complex or repetitive types, making the code clearer and easier to read.

typescript
"Here, we create an alias called StringOrNumber which can be a string or a number. Then we use it to declare a variable named id, which can take both numeric and text values."

Interfaces vs Types

While interfaces and types are similar in many respects, there are some key differences:

  • Interfaces: They are more appropriate for describing objects and can be extended.
  • Types: They are more flexible since they can describe more complex structures, such as union types and type aliases.

This image shows a comparison between interfaces and typesThis image shows a comparison between interfaces and types

In most cases, you can choose which to use based on your needs. TypeScript allows you to mix interfaces and types within the same project.

Conclusion

In this chapter, we have learned to use interfaces and types in TypeScript to define more clear and precise data structures. Interfaces are ideal for describing the shape of objects, while types give us additional flexibility with aliases and union types.


Ask me anything