Satisfy TypeScript by accommodating both array and non-array values within a single variable

I am looking to implement an array of Payments for each Rent instance, but I also want the flexibility to pass either a single Payment object or an array of Payment objects through the constructor...

However, the issue arises when I try to assign this.payment on the second occurrence and receive an error stating: "Type '(Payment | Payment[])[]' is not assignable..."

Here's the code snippet:


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 understand that I could always use [Payment] even when creating just one, but I prefer having multiple options available.

Answer №1

payment within the else statement remains as Payment|Payment[].

To address this issue, verify if it belongs to the Payment class and keep in mind that null could be passed as well:

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 = []; // Alternatively, consider throwing an error here depending on your preference
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for obtaining an AccessToken from LinkedIn's API for Access Token retrieval?

We have successfully implemented the LinkedIn login API to generate authorization code and obtain access tokens through the browser. https://i.sstatic.net/0dfxd.png Click here for image description However, we are looking to transition this functionality ...

Exploring the use of cell arrays and matrices in mex functions for efficient indexing and element access

I am currently working on writing a C++ mex function to loop through a cell array containing matrices of varying sizes. In Matlab, I was able to achieve this using the following code: function Z = myFunction(X, Z, B) for i = 1:size(X, 1) for j = 1:si ...

Tips for paginating a Laravel collection without using keys:

My task involves paginating an array of values with keys (e.g., 0,1,2) and extracting the values without their keys. Initially, the array looks like this: array:11 [ 0 => {#829 +"id": 2417 +"date": "2019-12-24 15:05:04" +"eventName": "At ...

Next.js routing can sometimes be unpredictable, especially when navigating from a nested route

I recently set up a directory named dashboard within the pages folder, and it contains the following files: index.tsx customers.tsx invoice.tsx items.tsx When a user navigates to http://localhost:3000/dashboard, the index.tsx page is displayed. However, ...

Issues with typescript compiler when using React-beautiful-dnd

I recently updated react and react-beautiful-dnd to the newest versions and now I am encountering many type errors in my code: {sortedDimensions.map((dimension: any, index: number) => ( <Draggable key={index} ...

Tips for passing multiple arrays to a constructor in Java

I am encountering an issue when trying to pass a multiple array to a constructor. Is this even possible? public class First { public String[] a; public String[] b; public First(String[] a, String[] b){ this.a=a; this.b=b; } } Below is the code sn ...

Unexpected identifier error: Typescript interface name syntax is incorrect

I am currently learning Typescript and still navigating my way through it. I have extensively searched for a solution to the issue I am facing, but couldn't find one, hence I am seeking help here. The problem lies in a SyntaxError at the interface nam ...

Issue: Expressjs is throwing a TypeError due to an attempt to read the 'id' property of undefined

I am currently working on a registration function in expressjs, but I keep encountering the following error message: TypeError: Cannot read properties of undefined (reading 'id') This is my user model: Users.ts interface UserAttributes { id: ...

Is the interpretation of A[i][j] impacted by the way A is defined in C programming?

Imagine having a two-dimensional array called grid defined as double grid[5][5]. It is my understanding that the following statements are accurate: Upon declaring grid, a continuous block of memory is assigned for 25 doubles, no more and no less; When an ...

What is the most effective way to programmatically select checkboxes based on array values in

Trying to keep it concise :) Working on a project that generates multiple pages of thumbnail images with checkboxes. The total thumbnails vary and are sorted into 1000 item html pages, called by a parent html page via iframe. Goal is for users to check che ...

Analyzing nested arrays against dictionary keys

Here is the array I am working with: [[ 36 119] [ 36 148] [ 36 179] [ 67 209] [ 69 84] [ 96 240]] In addition, I have a dictionary that looks like this: {84: [36, 119], 85: [36, 148], 86: [36, 160]} My goal is to identify if any values from the arra ...

Create a collection of unique objects using a specific key for each object in the array

Is it possible for TypeScript to define an array that enforces a unique key constraint for specified objects? Check out this demo showing the constraints. type Magician = { distinctKey: string; lastName: string; }; // How, if at all, can we make lin ...

esBuild failing to generate typescript declaration files while running in watch mode

Recently dove into using edBuild and I have to say, it's been a breeze to get up and running - simple, fast, and easy. When I execute my esBuild build command WITHOUT WATCH, I can see that the type files (.d.ts) are successfully generated. However, ...

Utilizing Angular 2's NgFor directive in SVG Elements

I want to use ngFor to draw an SVG Element that consists of lines. I am struggling with the implementation and need some help fixing the code. Here is what I have so far: my-component.js: import {Component} from 'angular2/core'; @Component({ ...

Navigating an array in pig, step by step

I am working with records that have various structures, including: "event" : [ {"x":"1","y":"2"} , {"x":"5","y":"2"}] "event" : [ {"random":"r", "pol" : "t", "a" : "b"} , {"x":"4","y":5"}] "event" : [ {"random":"f", "pol" : "w", "a" : "r"} , {"x":"12","y" ...

How do ptr[i] and *(ptr + i) differ from each other?

When working with a pointer to an array, I've always accessed the elements using an indexer like myPtr[i] = stuff. However, while reviewing the implementation of BitConverter, I noticed that elements were being accessed by using *(myPtr + i) = stuff. ...

Tips for sorting through an array by odd or even index values

Is there a way to filter out array entries based on odd or even index numbers? Array ( [0] => string1 [1] => string2 [2] => string3 [3] => string4 ) I am looking to remove the entries with indexes [0] and [2]. For example, if I ...

Assigning a specific data type to an object in TypeScript using a switch case statement

I am currently developing a React Native app using TypeScript. As part of my development, I am creating a handler with a switch case structure like the one below: export const handleMessageData = (dispatch: Dispatch, messageData: FCMMessage): void => ...

Utilizing TypeScript with React to dynamically select which component to render

My task seemed simple at first: to render a React component based on its name/type. Here is an example of how it is used: // WidgetsContainer.ts // components have a difference in props shape! const componentsData = [ { type: 'WIDGET_1', ...

The parameter 'To' cannot be assigned the argument of type '{pathname: string; shipment: TShipment;}'

Is there anyone who can assist me with a Typescript issue I'm currently facing? Upon running tsc in my project, I encountered the following error: I am getting the error saying that 'Argument of type '{ pathname: string; item: Item; }' ...