How can strict type checking be implemented in Angular for the returned response?
1. Utilize a data.json file for temporary API purposes
[
{
"name": "Someone 1",
"comment": "comment 1",
"line": "line 1"
},
{
"name": "Someone 2",
"comment": "comment 2",
"line": "line 2"
},
{
"name": 3,
"comment": "comment 3",
"line": "line 3"
}
]
- Define a model interface
export interface Model {
name: number;
comment: string;
line: string;
}
3. Service class app.service.ts
export class AppService {
constructor(private _http: HttpClient) {}
private api = "../api/data.json";
loadData(): Observable<Model[]> {
return this._http.get<Model[]>(this.api);
//.pipe(tap((data) => console.log("All:" + JSON.stringify(data))));
}
loadSingle(): Observable<Model> {
return this.loadData().pipe(map((data: Model[]) => data[2]));
}
}
4. Component class app.component.ts
export class AppComponent implements OnInit {
myvarArray: Model[];
myvarSingleton: Model;
constructor(private _appService: AppService) {}
ngOnInit() {
this._appService.loadData().subscribe((data) => {
this.myvarArray = data;
});
this._appService.loadSingle().subscribe((data) => {
this.myvarSingleton = data;
console.log(data.name + ":" + data.comment);
});
}
}
5. app.component.html
<h1>Printing obj data</h1>
<ul *ngFor="let data of myvarArray">
<li>{{ data.name }} -- {{ data.line }}</li>
</ul>
<h1>Printing Single data</h1>
<span>{{ myvarSingleton.name }}</span>
Is there a way to implicitly implement type checking so that the values in the data.json match the types declared in the interface? I am concerned that even if "name" is specified as a number, it does not throw an error during compilation when the data is returned to app.component. Is there a way to check this without using explicit validation functions?
[Edit] Additionally, why am I receiving an error stating "undefined property on myvarSingleton.name" even though the property is defined in the interface (but the data displays correctly on the page)? And why does it occur three times?
The console shows an error mentioning that "name" is undefined