Home > Software design >  call interface in Angular
call interface in Angular

Time:03-18

I have an interface from the BE like this:

export interface DailyGoal extends Base {
  date: Date;
  percentage: number;
}

Now I'm trying to refer to that in my component.ts file

import { DailyGoal } from '../../interfaces';
  dailyGoal: DailyGoal[] = [];

But I don't understand how to push the variable that I have into the date and percentage. I created this function that will give me the list of days that the user may choose (I still need to figure it out how to do the percentage)

   getDays(startDate: Date, endDate: Date) {
        const dates = [];
        const percentage = [];
        const currentDate = startDate;
        while (currentDate < endDate) {
          dates.push(new Date(currentDate));
          currentDate.setDate(currentDate.getDate()   1);
        }

// for (let date of dates) {

    // if (date.getDay() <= 5) {
    //   percentage.push(100);
    // 
    // } else date.getDay() > 5;
    // percentage.push(0);


 if (startDate && endDate)  dates.push(endDate);
    return dates;
  }

how can I push my "date" variable into the interface? hope you can help me, thank you so much

CodePudding user response:

Whenever you have both the date and percentage values, you can just call the push method on the dailyGoal array:

this.dailyGoal.push({ date: theDate, percentage: thePercentage });

CodePudding user response:

Typescript's core principle is that it looks at the shape of the objects. Also called duck typing, and interface is a useful construct that is used to give name and apply type checking to types (don't confue type with Typescript construct Type). So if your interface object is like

export interface DailyGoal extends Base {
  date: Date;
  percentage: number;
}

and Base interface is like this

export interface Base
{
number1: number;
string1: string;
}

then an object will be equivalent to DailyGoalinterface if it has all the 4 propeties from DailyGoal and Base interfaces.

this.dailyGoal.push({ date: theDate, percentage: thePercentage, number1: 0, string1: '' });

If you skip any of the member from any interface, you'll get ... type is missing following properties from type DailyGoal... kind of error.

If you don't want to assign values to the properties of Base interface you can make them optional by appending question mark (?) after the property name, like number1?:number. In that case you'll not have to provide the values of those properties (and they will be initialized by undefined by default ).

  • Related