I am experiencing challenges when trying to assign larger objects into smaller ones. To illustrate this issue, I will provide a simple example:
Let's say I have defined the Typescript interface:
export interface CrewMember {
name: string;
organizing_function?: string;
}
Now, I fetch an array of objects from a database that looks like this:
[{
id: "someID",
name: "Jack"
},{
id: "someOtherID",
name: "Jipp",
organizing_function: "Being good at stuff"
}]
My goal is to create an Array< CrewMember > to store the objects retrieved from the database. However, the objects from the database have an "ID" property that the "CrewMember" interface does not have. Therefore, I cannot simply assign them due to Typecript raising compatibility errors.
Initially, I attempted the following approach:
let crewmember : CrewMember = {
name: database[0].name,
organizing_function: database[0].organizing_function
};
However, this method is (1) laborious, especially when dealing with more extensive object types, and (2) complex because the organizing_function is optional. Consequently, I would need to implement numerous "IF" conditions to determine the presence of properties in the database object and assign them correctly.
What is the most efficient way to convert an object with unnecessary properties into another object with numerous optional properties in Typescript?
Any guidance on this matter would be greatly appreciated. Thank you.