为什么我不能投射使用TypeScript传播的对象的结果?

时间:2019-06-12 15:41:39

标签: javascript typescript

不是重复

我的问题与尝试找到对象的类型或类名无关。我的问题是关于将对象“转换”为类型-这源于对TypeScript及其工作方式的误解。这也与在投射时使用对象传播有关。

原始问题

我想使用对象传播将来自服务器的数据映射到客户端上定义的类。我试图摆脱将数据传递给构造函数并使用循环as illustrated here映射每个属性的麻烦。我尝试了以下方法:

//Data from server
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) //Shows 'object' not 'Book'
      var steps = bitem.steps.map(sitem => <Step>{ ...sitem, ...new Step() } as Step;);]
      book.steps = steps;
      return book;
 }

 console.log(typeof list[0]); //Expect 'Book' but get 'object'

我很好奇为什么键入Book的类型转换会产生object呢?有没有简单的方法可以做到这一点,或者我需要使用构造方法来完成这种映射吗?

1 个答案:

答案 0 :(得分:0)

关于这段代码,您可以通过以下技术将对象传递到constructor并创建相同的实例

 class Book implements IBook {
   id: number;
   name: string;
   authorName: string;
   steps : Step[] ;
   constructor(params: IBook) {
     Object.assign(this, params);
   }
 }

 class Step implements IStep {
    id: number;
    name: string;
    status: string = "unknown";
    processing: boolean = false;
    constructor(params: IStep) {
      Object.assign(this, params);
    }
 }


var list : Book[] = data.map((bitem:any)=> {
      var book = new Book(bitem);
      console.log(book) //Shows 'object' not 'Book'
      var steps = bitem.steps.map(sitem => (new Step(sitem)));
      book.steps = steps;
      retrun book;
 });

工作示例here