Happylab Logo
Published on

Day11: Learning TypeScript : Union Types and Intersection Types

Authors

#Day11: Learning TypeScript : Union Types / Intersection Types


Union Types (聯合型別)

Union Types allow a variable to hold values of different types. It is similar to the concept of || in JavaScript.

✅ Union Types use | to separate each type. For example, the type of id can be either a string or a number, but not any other type.

function printId(id: number | string) {
  console.log("Your ID is: " + id);
}
printId(101); //ok
printId("202"); //ok

❌ If a boolean value is used, it will throw an error.

// Error
printId({ myID: 22342 });
// error: Argument of type '{ myID: number; }' is not assignable to parameter of type 'string | number'.

Accessing Properties or Methods of Union Types

When TypeScript is unsure of the type of a variable that is a Union Type, we can only access properties or methods that are common to all types in the Union.

✅ Using properties that exist in both types is fine.

function printId(id: number | string) {
    console.log(id.toString());
}

❌ If different properties are used, it will throw an error, as the toUpperCase property does not exist on the number type.

function printId(id: number | string) {
  console.log(id.toUpperCase());
}

//error: Property 'toUpperCase' does not exist on type 'string | number'.

✅ To resolve different situations, we can use typeof to check the type. The official documentation refers to this behavior as Narrowing.

function printId2(id: number | string) {
  if (typeof id === "string") {
    console.log(id.toUpperCase());
  } else {
    console.log(id.toFixed(2));
  }
}

Intersection Types (交集型別)

Intersection Types allow you to combine multiple types into one. This means that a variable can hold values that satisfy all the types combined.

interface Person {
  name: string;
}

interface Employee {
  employeeId: number;
}

type EmployeePerson = Person & Employee;

const employee: EmployeePerson = {
  name: "John",
  employeeId: 123,
};

In the next article, we will continue discussing Intersection Types. See you tomorrow!


References

https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types