Skip to main content

Type Aliases & Interfaces in TypeScript (Live Playground)

In this tutorial, we will explore type aliases and interfaces in TypeScript. Understanding how to use type aliases and interfaces will enable you to create reusable and flexible types, which can help you write clean and maintainable code.

Type Aliases

Type aliases allow you to create a new name for a type. Type aliases can be used to simplify complex types or create more descriptive names for commonly used types. To create a type alias, use the type keyword followed by the alias name and the type it should represent:

TypeScript
type UserID = number;

function getUser(id: UserID): string {
// ...
}

In this example, we create a type alias UserID for the number type. We can now use UserID as a type throughout our code, making it more descriptive and easier to understand.

Live Playground, Try it Yourself

Interfaces

Interfaces are a powerful way to define and enforce the shape of an object. Interfaces allow you to specify the properties and methods that an object should have. To create an interface, use the interface keyword followed by the interface name:

TypeScript
interface User {
id: number;
name: string;
age?: number;
}

function greetUser(user: User): string {
return `Hello, ${user.name}!`;
}

In this example, we create an interface User with properties id, name, and an optional property age. We then use the User interface as a type for the user parameter in the greetUser function.

Live Playground, Try it Yourself

Differences Between Type Aliases and Interfaces

While type aliases and interfaces can often be used interchangeably, there are some key differences between them:

  1. Type aliases can represent any type, not just objects, while interfaces are specifically used for defining object shapes.
  2. Interfaces can be extended and merged, whereas type aliases cannot.
  3. Type aliases are more flexible and can represent union types, intersection types, and mapped types.

When to Use Type Aliases and Interfaces

In general, you should use interfaces when defining the shape of an object, especially if you need to extend or merge multiple interfaces. On the other hand, use type aliases for simpler type definitions or when you need to represent more complex types, such as union types or intersection types.

Conclusion

In this tutorial, we have explored type aliases and interfaces in TypeScript. Understanding how to use type aliases and interfaces effectively will enable you to create reusable and flexible types, which can help you write clean and maintainable code.