0

I want to have a array of Payment(s) for every Rent, but I want to be able to pass one or more Payments through the constructor...

I am getting error that says: "Type '(Payment | Payment[])[]' is not assignable..." on the second appearance of this.payment

Code:

class Rent {
  payments: Payment[]
  date: Date

  constructor(date: Date, payment:Payment|Payment[]) {
    this.date = date
    if(payment instanceof Array){
      this.payments = payment
    }else{
      this.payments = [payment]
    }
  }

PS: I am aware that I could always use [Payment] while creating one, but I like to have options

1 Answer 1

1

payment in the else condition is still Payment|Payment[].

To fix this, check if it's an instance of Payment and remember that someone could pass in null:

class Rent {
    payments: Payment[];
    date: Date;

    constructor(date: Date, payment: Payment|Payment[]) {
        this.date = date;

        if (payment instanceof Array) {
            this.payments = payment;
        } 
        else if (payment instanceof Payment) {
            this.payments = [payment];
        }
        else {
            this.payments = []; // or throw an error here... depends what you want
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, wouldn't find this by myself

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.