I've been researching interfaces and type assertion. I've come across some helpful pages:
- Typescript parse json with class and interface
- How do I cast a json object to a typescript class (this one has nothing to do with TS!)
- Parse complex json objects with Typescript
- TS doc about interfaces
I'm starting to grasp the concept, and the basics seem pretty straightforward. However, I can't seem to find information on how to properly type a JSON object to an object used in my app, especially when dealing with HTTP requests.
For instance, let's say I have an Array of Teacher objects. Each Teacher has an id, name, and an Array of Students. Then, I have another class for Students that contains their attributes... and so on.
Somewhere in those resources, I read that if you don't need to perform actions on an object, having just an Interface is enough. But if you want to perform actions, you need a separate class. Is that correct?
In my actual Teacher class, it starts like this... :
export class Teacher {
private students: Array<Student>;
constructor(public id: string, public name: string) {
this.students = new Array<Student>();
}
public getStudents(): Array<Student> {
return this.students;
}
}
First off, how would I go about casting or asserting the type of a JS object to a Teacher object?
Currently, my code looks something like this:
Service:
getTeachers() {
return this.http.get('someUrl')
.map((res: Response) => res.json())
}
Component (Angular 2 Component):
export class ListComponent implements OnActivate {
id: string;
name: string;
teachers: Teacher[];
constructor(public _service: Service, public _router: Router) {
}
routerOnActivate(): void {
this._service.getTeachers()
.subscribe(teachers => this.teachers = teachers);
}
My interface would look like:
export interface TeacherJSON {
id: string,
name: string,
students: Array<Student>;
}
If the above interface is insufficient for performing actions on the object, how should I proceed? I know you can add methods to your interface, but the http, mapping, and subscribing process is confusing me, and I'm not sure how to implement it in my code!