Home > OS >  Why does interface in typescript behaves like model?
Why does interface in typescript behaves like model?

Time:03-29

This is my html code

<form #incomesForm="ngForm" (ngSubmit)="saveMonthlyIncome(incomesForm.value)">
    <ion-grid>
      <ion-row>
        <ion-col size="6">
          <ion-item>
            <ion-label position="floating">Monthly Income</ion-label>
            <ion-input ngModel name="amount"></ion-input>
          </ion-item>
        </ion-col>
        <ion-col size="6">
          <ion-button type="submit" color="dark">Save</ion-button>
        </ion-col>
      </ion-row>
    </ion-grid>
  </form>

Then in my ts file,

saveMonthlyIncome(income: Income){
    alert(income.amount);
  }

Income is an interface which as far as I understand, it is just a contract and cannot hold values. Why is it that the amount was saved in the income variable?

CodePudding user response:

The value itself is not stored in that interface because it can't hold values as you pointed, it's just a type of contract.

The value you get by submitting a form implements that interface, so it is consisted of the same properties. The value is just a part of that object that you passed as an argument and it has .amount property on it because it fulfills the Income interface.

CodePudding user response:

it is just a contract and cannot hold values

Yes, but it can be a contract like "there is an amount property, of type number", i.e.

interface Income {
    amount: number
}

Any object is-a Income if it has an amount, and that amount is-a number

  • Related