I'm having troubles with assigning bigger objects into smaller objects. But I think I can best describe it with a simple example:
Suppose I have declared the Typescript interface:
export interface CrewMember {
name: string;
organizing_function?: string;
}
I now retrieve from a database an array of objects like this:
[{
id: "someID",
name: "Jack"
},{
id: "someOtherID",
name: "Jipp",
organizing_function: "Being good at stuff"
}]
I want to create an Array< CrewMember > wherein to put the objects from the database. However, my problem is that the the objects from the database have an "ID" which "CrewMember" doesn't. Hence I cannot simply assign them because Typescript complains that the types are incompatible.
I first tried something like this:
let crewmember : CrewMember = {
name: database[0].name,
organizing_function: database[0].organizing_function
};
However this is (1) quite the amount of work as I have many different types that are much, much bigger than this and (2) difficult because organizing_function is an optional parameter. So, as I understand, I would have to write a ton of "IF" clauses to find out what properties are given or not on the database object and then assign correctly.
So what is the best way to approach "casting" an object with superfluous properties into another object with a lot of optional properties in Typescript?
Would really appreciate any help on this. Thank you in advance.
Typescript is just a compile-time tool: in the end everything is javascript and nothing is typed.
So what you call casting is different from, for example, what is called casting in Java (where a runtime check is done). In typescript you can write:
const a: { prop: string } = (4 as any)
and it won't be a problem at all, don't use it as a { prop: string }, it will fail, but the casting itself will be ok.
Now, if you retrieved a javascript object named data of type { id: string; name: string; organizing_function: string}[] from somewhere, you can write:
const members: CrewMember[] = data;
And that's all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With