I have an array object data get from backend api. like:
[
{name: 'react', age: 4},
{name: 'angular', age: 4},
...
{name: 'rxjs', age: 2}
]
And I definite a class
and an interface
, like this:
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);
});
so I can encapsulate some data model methods like book.getFullName()
I can use it like this:
const fullname = book.getFullName()
rather than this:
const fullname = book.firstName + ' ' + book.lastName
;
Is there a better way to do this? I am not sure my thought is the correct way or not.
The problem is how to convert a js
object to ts
class model according to a correct way.
Or, just definite the data interface
. Is it necessary to convert javascript
json data to typescript
class
model?
-- update --
especially, the nested data. like this:
const datas = [
{name: 'react', age: 2, tag: [{id: 1}, {id: 2}]}
]
If no methods are needed, just cast your data. Otherwise, you may copy the data to your class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With