Generic mapping function where type T & Q have the same keys but different property types

Generic mapping function where type T & Q have the same keys but different property types

When working with TypeScript, you may come across a situation where you need to map properties from one object to another, but the property types are different. In such cases, a generic mapping function can be useful to handle this scenario. In this blog post, we will explore different solutions to implement a generic mapping function where type T and Q have the same keys but different property types.

Solution 1: Using a mapped type

One way to solve this problem is by using a mapped type in TypeScript. We can define a generic mapping function that takes two types, T and Q, and maps the properties from T to Q based on the same keys. Here’s an example:


type MappingFunction = {
  [K in keyof T]: Q[K];
};

function mapProperties(source: T): MappingFunction {
  return source as MappingFunction;
}

// Example usage
interface Person {
  name: string;
  age: number;
}

interface Employee {
  name: string;
  age: string;
}

const person: Person = {
  name: "John Doe",
  age: 25,
};

const employee: Employee = mapProperties(person);

console.log(employee);

The above code defines a generic mapping function called mapProperties that takes a source object of type T and returns a mapped object of type Q. The MappingFunction type is a mapped type that maps the properties from T to Q based on the same keys. In the example usage, we map properties from a Person object to an Employee object.

Solution 2: Using a type assertion

Another solution is to use a type assertion to explicitly tell TypeScript that the source object can be treated as the target object. Here’s an example:


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

interface Employee {
  name: string;
  age: string;
}

function mapProperties(source: T): Q {
  return source as Q;
}

// Example usage
const person: Person = {
  name: "John Doe",
  age: 25,
};

const employee: Employee = mapProperties(person);

console.log(employee);

In this solution, the mapProperties function takes a source object of type T and returns a target object of type Q. We use a type assertion (source as Q) to tell TypeScript that the source object can be treated as the target object. This allows us to map properties from the Person object to the Employee object.

Conclusion

In this blog post, we explored two solutions to implement a generic mapping function where type T and Q have the same keys but different property types. The first solution uses a mapped type to map properties from the source object to the target object, while the second solution uses a type assertion to explicitly tell TypeScript about the mapping. Both solutions can be used depending on your specific requirements.


Posted

in

by

Tags:

Comments

Leave a Reply

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