Home > Software design >  how to write an interface in angular
how to write an interface in angular

Time:12-07

This is the response I am getting from the backend. I want to write an interface Model for this where userIds can be any number. How to write a model for this?

{
    "courseId": 1,
    "userIds": [
      "46071424",
      "46076456",
    ],
    "endDate": "2022-03-29"
}

CodePudding user response:

You should check out the interface docs for Typescript. https://www.typescriptlang.org/docs/handbook/2/objects.html

UserId in you example response look like strings.

So for

{
    "courseId": 1,
    "userIds": [
      "46071424",
      "46076456",
    ],
    "endDate": "2022-03-29"
}

your interface could be

interface IModel {
  courseId: number;
  userIds: string[];
  endDate: string;
}

CodePudding user response:

export interface Course {
  courseId: number; 
  userIds: string[];
  endDate: string;
}

CodePudding user response:

TS Object Types

Try this:

interface number{
   courseId: number;
   userIds: any;
   endDate: string;
}

CodePudding user response:

https://www.typescriptlang.org/docs/handbook/interfaces.html

// model 1

interface backendModel{
    courseId : number,
    userIds? : string[],
    endDate?: string
}

// ex :

const model : backendModel = 
    {
        "courseId": 1,
        "userIds": [
          "46071424",
          "46076456",
        ],
        "endDate": "2022-03-29"
    };



// model 2

interface backendModel2{
    courseId : Number,
    userIds? : Number[],
    endDate?: Date
}


const model2 : backendModel2 = 
    {
        "courseId": 1,
        "userIds": [
         Number("46071424"),
         Number( "46076456"),
        ],
        "endDate": new Date("2022-03-29")
    };

// model 3 if all fields are required 

interface backendModel3{
    courseId : number,
    userIds : string[],
    endDate : string
}

CodePudding user response:

Just try http://json2ts.com/. You can convert any JSON to TS from it

  • Related