Ask Your Question
4

What is the approach for mapping an object with nested objects/types in Typescript?

asked 2023-05-17 01:38:56 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-17 01:55:01 +0000

woof gravatar image

The approach for mapping an object with nested objects/types in Typescript involves recursively iterating through the object's properties and mapping any nested objects/types as well. This can be accomplished using a combination of interfaces, classes, and helper functions.

  1. Define the interface for the object being mapped, including any nested object/types.
interface Person {
  name: string;
  age: number;
  address: {
    street: string;
    city: string;
    state: string;
  };
}
  1. Create a class that implements the interface and provides a method for mapping the object.
class PersonModel implements Person {
  name: string;
  age: number;
  address: {
    street: string;
    city: string;
    state: string;
  };

  constructor(person: Person) {
    this.name = person.name;
    this.age = person.age;
    this.address = person.address ? new AddressModel(person.address) : null;
  }

  toJson(): object {
    return {
      name: this.name,
      age: this.age,
      address: this.address ? this.address.toJson() : null,
    };
  }
}
  1. Create a similar class for any nested objects/types, and use the constructor to recursively map the object.
class AddressModel implements Address {
  street: string;
  city: string;
  state: string;

  constructor(address: Address) {
    this.street = address.street;
    this.city = address.city;
    this.state = address.state;
  }

  toJson(): object {
    return {
      street: this.street,
      city: this.city,
      state: this.state,
    };
  }
}
  1. Use a helper function or library to instantiate the top-level class and map the object.
function mapPerson(person: Person): object {
  const personModel = new PersonModel(person);
  return personModel.toJson();
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-17 01:38:56 +0000

Seen: 8 times

Last updated: May 17 '23