Step 7 – Union and intersection types in TypeScript

image 2

Play Store Application link – Java to TypeScript in 14 Steps – App on Google Play

In TypeScript, union and intersection types are like flexible tools that help you define variables and functions more precisely. Think of them as ways to create complex data structures, similar to how you might use interfaces and class inheritance in Java.

Union Types

Union types let you declare a variable that can hold multiple types of values. It’s like having a variable that can be either an int or a String in Java. You use the | symbol to separate the types.

Example:

function printId(id: number | string) {
  console.log(`ID is: ${id}`);
}

printId(101); // Output: ID is: 101
printId("abc"); // Output: ID is: abc

Java Comparison:

In Java, you might use method overloading to handle different types:

public void printId(int id) {
  System.out.println("ID is: " + id);
}

public void printId(String id) {
  System.out.println("ID is: " + id);
}

Scenario:

Imagine you’re working with an API that can return either a number or a string. You might use a union type to handle both cases:

async function fetchData(): Promise<number | string> {
  const response = await fetch("https://example.com/data");
  const data = await response.json();
  if (typeof data === "number") {
    return data;
  } else {
    return data.message;
  }
}

const result = await fetchData();
if (typeof result === "number") {
  console.log(`The data is a number: ${result}`);
} else {
  console.log(`The data is a string: ${result}`);
}

Intersection Types

Intersection types allow you to combine multiple types into one. It’s like creating a class in Java that implements multiple interfaces.

Example:

interface Person {
  name: string;
  age: number;
}

interface Employee {
  id: number;
  department: string;
}

type EmployeeInfo = Person & Employee;

const employee: EmployeeInfo = {
  name: "Alice",
  age: 30,
  id: 101,
  department: "Sales",
};

Java Comparison:

In Java, this is similar to implementing multiple interfaces:

interface Person {
  String getName();
  int getAge();
}

interface Employee {
  int getId();
  String getDepartment();
}

class EmployeeInfo implements Person, Employee {
  private String name;
  private int age;
  private int id;
  private String department;

  // constructor and methods
}

Scenario:

Suppose you need to represent a user who is both a person and an employee. You combine both sets of properties into a single type:

const user: EmployeeInfo = {
  name: "John",
  age: 25,
  id: 123,
  department: "HR",
};

In summary, union types let you handle multiple possible types for a variable, while intersection types let you combine different types into one. Both concepts are powerful tools for creating flexible and maintainable TypeScript code, much like using interfaces and inheritance in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *