Home > Software engineering >  Ionic Make the type of a field in a model a choice between two other models
Ionic Make the type of a field in a model a choice between two other models

Time:09-22

I have this model

import { Bank } from './bank.model';
import { Beneficiary } from './beneficiary.model';
import { Category } from './category.model';
import { Wallet } from './wallet.model';

export class Expense {
  constructor(
    public id: string,
    public amount: number,
    public paidFrom: [Bank, Wallet],
    public beneficiary: Beneficiary,
    public category: Category,
    public description: string,
    public date: Date
  ) {}
}

I want the field paidFrom to be only an object of bank or wallet, anything else will be an error. How can I achieve this?

CodePudding user response:

In such situation, it is desirable to use union types. A union type is a type formed from two or more other types, representing values that may be any one of those types.

So you can use something like this:

public paidFrom: Bank | Wallet;
  • Related