Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design typescript model for response?

How do I design my model in typescript where I got below response?

{
    "data":[
            {
                "name": "XYZ",
                "id": "1"
            },
            {
                "name" :"Abc",
                "id": "2"
            }
        ]
}

what I tried :

export class responseModel<T>{
    data:T;
}

export class model{
    name:string;
    id: number;
}

What is your recommendation? all data will come as part of { data: THE_DATA_OBJECT }

{
    data: []
}

getInfo(): Observable<responseModel<model[]>> {
    // API HTTP Call
}
like image 376
Var Avatar asked Mar 05 '23 09:03

Var


1 Answers

A class is unsuitable for declaring a type that represents an HTTP response. Use interface or type instead because the deserialized JSON values that result from HTTP requests will never be instances of a class

@Angular StyleGuide
Consider using an interface for data models.

export interface Model{
        id: number;
        name: string;
    }

export interface ResponseModel{
         data:Array<Model>;
  }

getInfo(): Observable<responseModel>{
return this._httpClient.get<resposneModel>('url);
}
like image 134
Vikas Avatar answered Mar 17 '23 06:03

Vikas