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

Tips for choosing and unchoosing rows in angular 6

I am looking to extract the values from selected rows and store them in an array. However, I also need to remove a row from the result array when it is deselected. The issue with my current code is that every time I click on a row, the fileName values are ...

Is it possible to store input from a multiline TextArea into an array using NetBeans?

I'm currently working on a task that involves taking a list of names from a multiline TextArea, putting them into an array, making some modifications, and then displaying them in a list. However, I've encountered an issue with extracting the inp ...

Managing errors with the RxJS retry operator

I'm facing an issue with my RxJS code where I need to continuously retry a data request upon failure while also handling the error. Currently, I am using the retry operator for this purpose. However, when attempting to subscribe to the retry operator ...

Utilizing AngularJs to differentiate between arrays and strings within an HTML template

I'm currently facing a challenge with creating a dynamic HTML template. In order to present data in a table, I need to distinguish between a regular String and an Array. Firstly, the HTML template is embedded within another template using the data-ng- ...

Is ts-node necessary for using TypeScript in Node.js?

Having trouble setting up a Node.js application in Visual Studio Code using TypeScript due to issues with importing modules. Initially, I created an index.ts file with the import statement -> import config from './app/config.json'; This resu ...

Contrast a multi-dimensional array against a regular array and populate any missing elements

My array consists of various waste categories and corresponding values for specific months: Array ( [Recycling] => Array ( [May 14] => 7040 [Jul 14] => 3920 [Aug 14] => 14560 [Sep 14] ...

Warning in TypeScript: TS7017 - The index signature of the object type is implictly assigned as type "any"

An alert for TypeScript warning is popping up with the message - Index signature of object type implicitly has any type The warning is triggered by the following code block: Object.keys(events).forEach(function (k: string) { const ev: ISumanEvent ...

A specialized <T> interface, now enhanced with additional functionalities

Looking to create a generic type (with parameter T) that exhibits the following behavior: If K represents a key of T, allow the value type to be either T[K] | ((params?: Partial<T>) => string) If K is not a key of T, allow the value type to be ( ...

Inactive function

I have a function that inserts my articles and I call this function on my page. There are no errors, but the next function retrieveAllArticles() is not being executed. public saveAllArticles(article) { for(let data in article) { this.db.exec ...

Routing with nested modules in Angular 2 can be achieved by using the same

Encountering a common issue within a backend application. Various resources can be accessed through the following routes: reports/view/:id campains/view/:id suts/view/:id certifications/view/:id Note that all routes end with the same part: /view/:id. ...

When the network connection is active, the observable will retry and repeat based on other observable signals

Sample snippet: const networkConnected = new BehaviorSubject<boolean>(false); setTimeout(networkConnected.next(true), 10000); webSocket('ws://localhost:4949') .pipe( retryWhen(errors => errors.pipe(delay(10000), filter(() => n ...

Error message encountered following the removal of an undesirable type from an array in Typescript

When working with TypeScript, I am facing an issue. I have an array defined as Array<string|undefined, and my goal is to filter out the undefined values from this array and assign the resulting array to a variable of type Array<string>. However, I ...

What is the best way to save String arrays to a text file in Java with the help of PrintWriter?

Looking for assistance in writing the contents of array objects to a text file using Printwriter. I'm a beginner, so any simple ideas would be greatly appreciated! Astronauts[0][0] = new Passengers(-1, "", 1, 0, 0, "", "", 0, "", "", "", "", ""); ...

Issues with type errors in authentication wrapper for getServerSideProps

While working on implementing an auth wrapper for getServerSideProps in Next.js, I encountered some type errors within the hook and on the pages that require it. Below is the code for the wrapper along with the TypeScript error messages. It's importan ...

Mapping an array of objects within another array of objects

I have a collection of objects that I looped through to extract the content: const teamSliderContent = [ { Description1: 'Chef. Mordy Wenk', Title: 'Head of the Chief staff.', id: 1, }, { Desc ...

Merge JSON objects while retaining duplicate keys

I am looking to merge two arrays containing JSON objects while retaining duplicate keys by adding a prefix to the keys. In this specific scenario, the data from 'json2' is replacing the data from 'json1' due to having identical keys, bu ...

The setInterval function continues executing even after the page has been changed

I'm encountering an issue with my function where it continues to run even after the page has changed, resulting in an error. How can I go about stopping this behavior? Thank you! componentDidMount() { var current = 0; var slides = document.g ...

Designing php/mysql data in a container

After successfully converting an ordered list output into a div output, I now face the challenge of stacking arrays on top of each other (and side by side with the two divs) like they would in an ordered list. Here is the original code snippet: <?php ...

Exploring TypeScript Module Importation and WebPack Integration

Struggling with WebPack's injection of imported dependencies for a TypeScript project. The first challenge is getting TypeScript to recognize the imported module. In the header.ts file, there is a declaration of a module nested under vi.input, export ...

How can I utilize the color prop in the theme file to style new variants more comprehensively with MUI theming?

I am working on creating a custom variant for an MUI button where the color specified in the color prop should be applied as both the border and text color. While the MUI documentation offers a suggested approach, it requires addressing each available col ...