typescript,如何将对象传递给类的构造函数以进行实例化

时间:2017-08-03 03:24:00

标签: typescript

我有一个来自后端api的数组对象数据。喜欢:

[
 {name: 'react', age: 4},
 {name: 'angular', age: 4},
 ...
 {name: 'rxjs', age: 2}
]

我确定classinterface,如下:

interface IBook {
  name: string;
  age: number;
}

class Book{
  book: IBook;

  constructor(book: IBook) {
    this.book = book;
  }

  //I can definite some method here: 

  getFullName() {
    return this.book.firstName + ' ' + this.book.lastName;
  }

  isValid() {
    return book.name.length > 0;
  }

}

//when get the data
const dataModels = datas.map(data => {
  return new Book(data);
});

所以我可以封装一些数据模型方法,如book.getFullName()

我可以这样使用它:

const fullname = book.getFullName()

而不是:

const fullname = book.firstName + ' ' + book.lastName;

有更好的方法吗? 我不确定我的想法是否正确。

问题是如何根据正确的方式将js对象转换为ts类模型。

或者,只需确定数据interface即可。是否有必要将javascript json数据转换为typescript class模型?

- 更新 -

尤其是嵌套数据。像这样:

const datas = [
 {name: 'react', age: 2, tag: [{id: 1}, {id: 2}]}
]

1 个答案:

答案 0 :(得分:3)

如果不需要任何方法,只需投射数据即可。否则,您可以将数据复制到您的班级。

let datas = [
 {name: 'react', age: 4, extra: { value: 1 }},
 {name: 'angular', age: 4, extra: { value: 2 }},
 {name: 'rxjs', age: 2, extra: { value: 3 }}
]

interface IBook {
  name: string;
  age: number;
}

interface Extra {
    value: number;
}

let books: IBook[] = datas;
console.log(books[0].name); // react

class Book {
    name: string;
    age: number;
    extra: Extra;

    constructor(data: any) {
        for (let key in data) {
            this[key] = data[key];
        }
    }

    getFullName() {
        return this.name;
    }

    isValid() {
        return this.name.length > 0;
    }
}

let books2 = datas.map(book => new Book(book));
console.log(books2[1].getFullName()); // angular
console.dir(books2[0].extra.value); // 1
相关问题