我有一个从后端 api 获取的数组对象数据。喜欢:
[
{name: 'react', age: 4},
{name: 'angular', age: 4},
...
{name: 'rxjs', age: 2}
]
我确定一个class
and an 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
model?
- 更新 -
特别是嵌套数据。像这样:
const datas = [
{name: 'react', age: 2, tag: [{id: 1}, {id: 2}]}
]