Type aliases in TypeScript allow you to create a new name for a type. This can be particularly useful for simplifying complex type definitions, making your code more readable, and reusing types across your codebase.

Key Concepts

  1. Definition: A type alias is defined using the type keyword followed by the alias name and the type it represents.
  2. Usage: Type aliases can be used for primitive types, object types, union types, intersection types, and more.
  3. Differences from Interfaces: While both type aliases and interfaces can be used to define object shapes, type aliases are more flexible as they can represent any type, not just objects.

Defining Type Aliases

Basic Type Alias

You can create a type alias for a primitive type:

type StringAlias = string;
type NumberAlias = number;

let myString: StringAlias = "Hello, TypeScript!";
let myNumber: NumberAlias = 42;

Object Type Alias

Type aliases can also be used to define the shape of an object:

type User = {
  id: number;
  name: string;
  email: string;
};

let user: User = {
  id: 1,
  name: "John Doe",
  email: "[email protected]"
};

Union and Intersection Types

Type aliases are particularly useful for union and intersection types:

type ID = number | string;

let userId: ID = 123;
userId = "abc123";

type Admin = {
  role: "admin";
  permissions: string[];
};

type Guest = {
  role: "guest";
  accessLevel: number;
};

type UserRole = Admin | Guest;

let adminUser: UserRole = {
  role: "admin",
  permissions: ["read", "write", "delete"]
};

let guestUser: UserRole = {
  role: "guest",
  accessLevel: 1
};

Practical Examples

Example 1: Complex Object Type

type Address = {
  street: string;
  city: string;
  country: string;
};

type Person = {
  name: string;
  age: number;
  address: Address;
};

let person: Person = {
  name: "Alice",
  age: 30,
  address: {
    street: "123 Main St",
    city: "Wonderland",
    country: "Fantasy"
  }
};

Example 2: Function Type Alias

You can also create type aliases for function types:

type GreetFunction = (name: string) => string;

const greet: GreetFunction = (name) => {
  return `Hello, ${name}!`;
};

console.log(greet("Bob")); // Output: Hello, Bob!

Exercises

Exercise 1: Define a Type Alias for a Product

Define a type alias for a Product object with the following properties:

  • id: number
  • name: string
  • price: number
  • inStock: boolean

Create a variable of type Product and assign appropriate values to it.

Solution

type Product = {
  id: number;
  name: string;
  price: number;
  inStock: boolean;
};

let product: Product = {
  id: 101,
  name: "Laptop",
  price: 999.99,
  inStock: true
};

Exercise 2: Union Type Alias

Define a type alias Result that can be either a Success object or an Error object. The Success object should have a status property with the value "success" and a data property of type string. The Error object should have a status property with the value "error" and a message property of type string.

Create variables of type Result for both success and error cases.

Solution

type Success = {
  status: "success";
  data: string;
};

type Error = {
  status: "error";
  message: string;
};

type Result = Success | Error;

let successResult: Result = {
  status: "success",
  data: "Operation completed successfully."
};

let errorResult: Result = {
  status: "error",
  message: "An error occurred during the operation."
};

Common Mistakes and Tips

  • Mistake: Confusing type aliases with interfaces. Remember that type aliases can represent any type, not just objects.
  • Tip: Use type aliases to simplify complex type definitions and improve code readability.
  • Tip: Combine type aliases with union and intersection types to create flexible and reusable type definitions.

Conclusion

Type aliases are a powerful feature in TypeScript that allow you to create new names for types, making your code more readable and maintainable. They can be used for primitive types, object types, union types, intersection types, and more. By understanding and utilizing type aliases, you can write cleaner and more efficient TypeScript code.

In the next topic, we will explore Type Guards, which help you write safer and more robust code by narrowing down types at runtime.

© Copyright 2024. All rights reserved