Uniqueness in Question
My inquiry was not aimed at identifying the type or class name of an object. Rather, it delved into the concept of "casting" an object to a specific type, which arose from a misconception about TypeScript and its functionality. This query also pertained to utilizing Object spread while performing the casting process.
Distinctive Query
I aimed to utilize object spread to translate data received from the server into a client-defined class. My goal was to avoid manually passing data to a constructor and mapping each property through a loop, as demonstrated in a related query found here. The approach I attempted involved the following steps:
//Server Data
var data = [
{id: 1, name: "Book 1", authorName: "Author 1",
steps: [
{id: 1, name: "Step 1"},
{id: 2, name: "Step 2"}
]},
{id: 2, name: "Book 2", authorName: "Author 2",
steps: [
{id: 1, name: "Step 1"},
{id: 3, name: "Step 3"}
]}
];
interface IBook {
id: number;
name: string;
authorName: string;
steps:IStep[];
}
interface IStep {
id: number;
name: string;
status: string;
processing: boolean;
}
class Book implements IBook {
id: number;
name: string;
authorName: string;
steps : Step[] ;
}
class Step implements IStep {
id: number;
name: string;
status: string = "unknown";
processed: boolean = false;
}
var list : Book[] = data.map(bitem=> {
var book = <Book>{ ...bitem, ...new Book() } as Book;
console.log(book) //Displays 'object' instead of 'Book'
var steps = bitem.steps.map(sitem => <Step>{ ...sitem, ...new Step() } as Step;);]
book.steps = steps;
return book;
}
console.log(typeof list[0]); //Expected 'Book' but received 'object'
I'm intrigued by why the casting to type Book
results in an object
rather than the expected type. Is there a straightforward method to achieve this, or should I resort to the constructor approach for such mapping endeavors?