How can I store various data types in a single array in TypeScript?

I have a scenario I need help with.
Let's say we have two interfaces, Cats and Dogs. How can I create an array that can store both Cats and Dogs?

interface Cats {
  name: string;
  age: number;
}

interface Dog {
  owner: string;
}

const cat1: Cats = {
  name: "Jimmy",
  age: 5,
}

const dog1: Dogs = {
  owner: "Bobby",
}

// The line below is not functioning as expected
const animalsList: Array<Cats> | Array<Dogs> = [cat1, dog1];

The variable animalsList should be able to hold instances of both Cats and Dogs, but I am encountering errors like
"Type Dogs cannot be assigned to type Array<Cats>"

Answer №1

From my understanding of your question, you are looking to create an array that can accommodate both Cats and Dogs. The current syntax

Array<Cats> | Array<Dogs>
indicates that you can have either a) an array exclusively for Cats or b) an array exclusively for Dogs.

To address this issue, you need an array that is capable of holding both types. The correct way to achieve this is as follows:

public animalsList: Array<Cats | Dogs>;

The placement of the pipe (|) in the updated code signifies that this Array can store both Cats and Dogs simultaneously.

Another approach, suggested by @sunshine, is shown below:

public animalsList: (Cats | Dogs)[];

This alternative method functions in a similar manner.

Answer №2

Check out this complete example:

// Explore the TypeScript Playground, a platform designed for writing, sharing, and mastering TypeScript.

// There are three main ways to use it:
//
//  - Learn TypeScript in a safe environment where errors won't impact your work
//  - Experiment with TypeScript syntax and easily share your code with others
//  - Test different compiler features of TypeScript in a sandbox setting

const anExampleVariable = "Hello World"
console.log(anExampleVariable)

// For more language insights, click on "Examples" or "What's New" above.
// Start coding by removing these comments and let your imagination run wild.
  
class Cats {
    private name: String;
    constructor(name: String) {
        this.name = name;
    }
    public dump() { console.log(`I am cat ${this.name}`); }
}
class Dogs {
    private name: String;
    constructor(name: String) {
        this.name = name;
    }
    public dump() { console.log(`I am dog ${this.name}`); }
}

class Test {
    public animalsList : Array<Cats> | Array<Dogs> = Array();
}

const t = new Test();
t.animalsList = Array(new Cats('cat1'), new Cats('cat2'));
t.animalsList.forEach((v, i) => { v.dump(); });

t.animalsList = Array(new Dogs('pluto'), new Dogs('goofy'));
t.animalsList.forEach((v, i) => { v.dump(); });

// The following line fails
//t.animalsList = Array(new Dogs('pluto'), new Cats('cat2'));
//t.animalsList.forEach((v, i) => { v.dump(); });

Experiment with this code snippet on https://www.typescriptlang.org/play

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

Using Angular template to embed Animate CC Canvas Export

Looking to incorporate a small animation created in animate cc into an angular template on a canvas as shown below: <div id="animation_container" style="background-color:rgba(255, 255, 255, 1.00); width:1014px; height:650px"> <canvas id="canv ...

Invoking a Typescript function from the Highcharts load event

Struggling to call the TypeScript function openDialog() from the events.load of Highcharts? Despite using arrow functions, you are running into issues. Take a look at the code snippet below: events: { load: () => { var chart : any = this; ...

Cypress eliminating the "X-CSRFToken" header

There seems to be an issue with the Cypress test runner where it is removing X-CSRFToken from the request header, leading to a 403 Forbidden error. I have compared the headers between a manual run and a Cypress test run, and you can see the difference in t ...

"Typescript: Unraveling the Depths of Nested

Having trouble looping through nested arrays in a function that returns a statement. selectInputFilter(enteredText, filter) { if (this.searchType === 3) { return (enteredText['actors'][0]['surname'].toLocaleLowerCase().ind ...

Simulation service agent partnered with openApi backend

I am currently utilizing MSW along with the OpenAPI-backend package for my project. I aim to mock both the browser server and test server using OpenAPI specifications. With an available OpenAPI definition, I generate `generated.ts` for RTK Query (which is ...

Handling linting errors for getInitialProps return type in NextJS with Typescript

I've been grappling with this problem for an extended period, and despite numerous attempts, I haven't been able to resolve it. My issue revolves around a basic page named one.tsx. Its structure is as follows: The linting error that's plag ...

Breaking up and Substituting text within Angular 8's HTML structure

When I retrieve data from a REST api, I need to split the name parameter at '2330' and insert a line break. For example, if the name is: ABCD 2330 This is My Name, I want the output on my screen to appear as: ABCD 2330 This is My Name // this par ...

Modify the values of all cells within a specific column in a table by utilizing a 2D array for both rows and cells

https://codesandbox.io/s/1p770371j The demonstration above showcases a table where data can be modified in each cell, and the 2D array keeps track of which row and column the data changes occur. A new button has been added to the column header titles. Th ...

The TypeScript compiler is unable to locate the name 'window'

Within my Meteor/React project, I encounter the following line of code: let gameId = window.prompt("Please input the ID of the game you would like to load."); The TypeScript compiler presents an error during transpiling: Cannot find name 'window&apo ...

The Function-supported Operation is having trouble implementing a modification related to Geohash/Geopoint - the Object Type requires a String format

Summary: My function-based Action that tries to set a GeoPoint as a Geohash property is failing with an error suggesting it was anticipating a string. I have an Object Type with a String property that has been designated as a Geohash in the property edito ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

Update the CSS styling of a parent div based on the active state of specific child divs

I have a class with 4 distinct columns. div class="mainContent"> <div class="left-Col-1" *ngIf="data-1"> </div> <div class="left-Col-2" *ngIf="!data-1"> ...

Steps for enabling a function to return an undefined type

After extensive review, I have discovered that TypeScript has numerous hidden nuances, which make it less strict and accurate. I prefer to utilize 'undefined' as the return type for functions because it accurately reflects the reality of the sit ...

The compatibility issue between Bootstrap and Angular 2 is causing some challenges

Hey there, I recently enrolled in an Angular 2 course on udemy and everything was running smoothly until I encountered an issue while trying to install bootstrap. I followed the installation steps diligently, but whenever I attempt to add any bootstrap el ...

Consolidate all important values into a single NSMutable Array

Looking for a solution to combine multiple "ingredients" key values from a JSON file into one array? Here's a snippet of the JSON structure: { "locations": [ { "ingredients" : "Biscuits\n3 cups All-purpose Flour\n2 Tablespoons Ba ...

Ways to speed up the initial loading time in Angular 7 while utilizing custom font files

Storing the local font file in the assets/fonts folder, I have utilized 3 different types of fonts (lato, raleway, glyphicons-regular). https://i.stack.imgur.com/1jsJq.png Within my index.html under the "head" tag, I have included the following: <lin ...

The type '{}' does not contain a property named 'map'

Recently delving into TypeScript, and I'm curious about the process of typing an axios response when storing it in a state variable. I've initiated a basic API call from App.tsx, which returns the following object: {data: {…}, status: 200, s ...

Having trouble resolving TypeScript TS2322 error with Context API + useState hook in your React App?

Currently, I am working on a React Typescript project that utilizes the Context API to pass down a useState hook. export const AppContext = React.createContext(null); function App() { const [value, setValue] = React.useState(3); return ( <Ap ...

Tips for storing an unmatched result in an array with a Regexp

Is it possible to extract the unmatched results from a Regexp and store them in an array (essentially reversing the match)? The following code partially addresses this issue using the replace method: str = 'Lorem ipsum dolor is amet <a id="2" css ...

The validation process in Redux forms

Imagine we have the following types defined: interface MyFormFields { FirstName: string; LastName: string; } type FieldsType = keyof MyFormFields; const field1: FieldsType = "c"; const field2 = "c" as FieldsType; Now, I am looking to implemen ...