Skip to main content

TypeScript: Combining Types

Combining Types

Values can hold more than one type. Let's explore how to combine types in TypeScript.

Union Types

Union types allow a variable to hold values of two or more different types. This is particularly useful when a value can legitimately be of more than one type.

function printId(id: number | string) {
if (typeof id === "number") {
console.log("Your ID is a number:", id);
} else {
console.log("Your ID is a string:", id);
}
}

printId(101); // Outputs: Your ID is a number: 101
printId("202"); // Outputs: Your ID is a string: 202

In this example, the printId function accepts both number and string types for its parameter. This flexibility allows the function to handle IDs that might be represented in different formats.

Intersection Types

Intersection types are a way of combining multiple types into one. This means that a variable of an intersection type will have all the properties of all the types it combines. This is especially useful for mixing multiple types into a new one that possesses all attributes of the included types.

interface BusinessPartner {
name: string;
credit: number;
}

interface ContactDetails {
email: string;
phone: string;
}

type BusinessContact = BusinessPartner & Contact onDetails;

let contact: BusinessContact = {
name: "Company A",
credit: 5000,
email: "contact@companya.com",
phone: "123-456-7890"
};

console.log(contact);

Here, BusinessContact is an intersection type that includes all properties from BusinessPartner and ContactDetails. An instance of BusinessContact must contain all fields defined by both interfaces.

Type Aliases

Type aliases in TypeScript allow you to create a new name for a type. Type aliases are sometimes similar to interfaces but can name primitives, unions, tuples, and any other types that you'd need to define.

type Point = {
x: number;
y: number;
};

let drawPoint = (point: Point) => {
// Draw point at coordinates (point.x, point.y)
console.log(`Drawing at (${point.x}, ${point.y})`);
};

drawPoint({ x: 100, y: 200 });

Type aliases, such as Point here, make the code more readable and manageable, especially when complex type definitions are used frequently throughout the code.

Differences between Interfaces and Type Aliases

  • Interfaces: Can be extended or implemented, making them more flexible for defining object shapes and contracts.
  • Type Aliases: Are more suitable for defining complex types, such as unions or intersections, and for creating descriptive names for types.

A key thing to note is that aliases cannot be modified or extended after they are defined, whereas interfaces can be extended to add new properties or methods.

keyof Operator

The keyof operator in TypeScript is used to extract the set of keys from a given type as a literal or union type. This is often used for ensuring that only valid property names are passed as arguments.

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

type UserProperties = keyof User; // "id" | "name" | "age"

function getProperty(user: User, propertyName: UserProperties) {
return user[propertyName];
}

let user: User = { id: 1, name: "John Doe", age: 30 };
console.log(getProperty(user, "name")); // Outputs: John Doe

In this example, UserProperties is a union type of literal types extracted using keyof, which ensures that the getProperty function only accepts property names that actually exist on the User type.

Automated Amazon Reports

Automatically download Amazon Seller and Advertising reports to a private database. View beautiful, on demand, exportable performance reports.

bidbear.io