簡體   English   中英

typescript,如何將對象傳遞給類的構造函數以進行實例化

[英]typescript, How do I pass an object to a constructor of class for instantiation

我有一個從后端API獲取的數組對象數據。 喜歡:

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

我確定一個class和一個interface ,如下所示:

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}]}
]

如果不需要任何方法,只需投射數據即可。 否則,您可以將數據復制到您的班級。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM