'Why does interface in typescript behaves like model?
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?
Solution 1:[1]
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.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chaka15 |
| Solution 2 | Caleth |
