TypeScript Generic Object Types

While building a TypeScript project, I got a requirement where I had to handle different types of user profiles depending on the user’s state. Each profile had common fields but also unique details like beach preferences for California or BBQ choices for Texas. To handle this in a better way, I used TypeScript generic object types.

In this tutorial, I will explain how to use TypeScript generic object types to create flexible and reusable code.

Understanding TypeScript Generics

Before diving into generic object types, let’s briefly discuss what TypeScript generics are. Generics enable you to write reusable code components that can work with multiple types. They allow you to parameterize types, similar to how you parameterize values in functions.

For example, consider a simple identity function that takes an argument and returns it:

function identity<T>(arg: T): T {
  return arg;
}

In this example, T is a type variable that represents the type of the argument and the return value. You can call this function with any type, and TypeScript will ensure type safety:

const result1 = identity<string>("Hello, USA!");
console.log("result1:", result1);

const result2 = identity<number>(42);
console.log("result2:", result2);

Output:

Use TypeScript Generic Object Types

Check out: Set Default Values in TypeScript Interfaces

Defining Generic Object Types in TypeScript

Now, let’s explore how to define generic object types in TypeScript. Suppose you have an application that deals with user profiles from different states in the USA. Each state may have its own specific properties in addition to the common properties. You can create a generic object type to handle this scenario:

interface Profile<T> {
  name: string;
  age: number;
  state: string;
  additionalInfo: T;
}

In this example, Profile is a generic interface that takes a type parameter T. The additionalInfo property is of type T, allowing you to specify different types for different states.

Using Generic Object Types

Let’s see how you can use the generic Profile interface in practice. Consider the following examples:

interface CaliforniaInfo {
  hollywood: boolean;
  beaches: string[];
}

interface TexasInfo {
  cowboys: boolean;
  bbq: string[];
}

const johnProfile: Profile<CaliforniaInfo> = {
  name: "John Smith",
  age: 30,
  state: "California",
  additionalInfo: {
    hollywood: true,
    beaches: ["Venice Beach", "Santa Monica Beach"],
  },
};

const sarahProfile: Profile<TexasInfo> = {
  name: "Sarah Johnson",
  age: 25,
  state: "Texas",
  additionalInfo: {
    cowboys: true,
    bbq: ["Brisket", "Ribs"],
  },
};

Output:

Generic Object Types in TypeScript

In these examples, we define two interfaces, CaliforniaInfo and TexasInfo, which represent the additional properties specific to each state. We then create two profile objects, johnProfile and sarahProfile, using the generic Profile interface with the respective state-specific types.

Check out: Create an Object from an Interface in TypeScript

Creating Generic Functions

Generic object types can also be used in functions to create reusable and type-safe code. Let’s consider a function that updates a profile object:

function updateProfile<T>(profile: Profile<T>, updatedInfo: Partial<T>): Profile<T> {
  return { ...profile, additionalInfo: { ...profile.additionalInfo, ...updatedInfo } };
}

In this example, the updateProfile function takes a Profile object and an updatedInfo object of type Partial<T>, which allows partial updates. The function returns an updated Profile object with the merged additionalInfo.

Here’s how you can use the updateProfile function:

const updatedJohnProfile = updateProfile(johnProfile, {beaches: ["Malibu Beach"]});
const updatedSarahProfile = updateProfile(sarahProfile, {bbq: ["Sausage"]});

After Update:

Before update: {
  name: 'John Smith',
  age: 30,
  state: 'California',
  additionalInfo: {
    hollywood: true,
    beaches: [ 'Venice Beach', 'Santa Monica Beach' ]
  }
}
Updating with: { beaches: [ 'Malibu Beach' ] }
After update: {
  name: 'John Smith',
  age: 30,
  state: 'California',
  additionalInfo: { hollywood: true, beaches: [ 'Malibu Beach' ] }
}
updatedJohnProfile: {
  name: 'John Smith',
  age: 30,
  state: 'California',
  additionalInfo: { hollywood: true, beaches: [ 'Malibu Beach' ] }
}
Before update: {
  name: 'Sarah Johnson',
  age: 25,
  state: 'Texas',
  additionalInfo: { cowboys: true, bbq: [ 'Brisket', 'Ribs' ] }
}
Updating with: { bbq: [ 'Sausage' ] }
After update: {
  name: 'Sarah Johnson',
  age: 25,
  state: 'Texas',
  additionalInfo: { cowboys: true, bbq: [ 'Sausage' ] }
}
updatedSarahProfile: {
  name: 'Sarah Johnson',
  age: 25,
  state: 'Texas',
  additionalInfo: { cowboys: true, bbq: [ 'Sausage' ] }
}

Output:

Use Generic Object Types in TypeScript

Check out: Use TypeScript Interface Function Properties

Benefits of Using Generic Object Types in TypeScript

Using generic object types in TypeScript offers several benefits:

  1. Flexibility: Generic object types allow you to create reusable code components that can work with different object structures, making your code more flexible and adaptable to different scenarios.
  2. Type Safety: By specifying the type parameter for generic object types, TypeScript ensures type safety and catches potential type-related errors at compile time.
  3. Code Reusability: Generic object types enable you to write code that can be reused across multiple parts of your application, reducing duplication and improving maintainability.
  4. Improved Readability: By using descriptive type names and type parameters, generic object types make your code more self-explanatory and easier to understand.

Check out: Check if an Object is Type of Interface in TypeScript

Conclusion

In this TypeScript tutorial, we have learned how to use TypeScript generic object types to create flexible and reusable code. We learned how to define generic interfaces, use them with specific types, and create generic functions that can work with different object structures.

By using generic object types, we can write code that is safe and reusable. This is particularly useful when dealing with diverse data structures, such as user profiles from different geo locations.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.