Using a variety of objects in TypeScript arrays

How to effectively implement a superior class in TypeScript for an array containing diverse objects that inherit from the same class, without triggering errors?

This is my attempt:

interface IVehicle{
    modelName: string
}

interface ICar extends IVehicle{
    numberOfDoors: number,
    isDropTop: boolean
}

interface IBike extends IVehicle{
    hasDynamo: boolean
}


var vehicles: IVehicle[] =
    [
        {
            modelName: "carModelName", // Error
            numberOfDoors: 4,
            isDropTop: true
        },
        {
            modelName: "bikeModelName",
            hasDynamo: true
        }
    ]

Unfortunately, this approach is causing errors.

I can only add objects of the parent interface IVehicle to avoid any error messages.

Answer №1

Rectifying the syntax errors allows you to specify the type of each element in the array individually.

interface IVehicle {
    modelName: string
}

interface ICar extends IVehicle {
    numberOfDoors: number,
    isDropTop: boolean
}

interface IBike extends IVehicle {
    hasDynamo: boolean
}

let vehicles: IVehicle[] =
    [
        {
            modelName: "carModelName",
            numberOfDoors: 4,
            isDropTop: true,
        } as ICar,
        {
            modelName: "bikeModelName",
            hasDynamo: true
        } as IBike
    ]

Alternatively, you can simply change the type of the array to an array of vehicle, car, or bike like this:

let vehicles: Array<IVehicle | ICar | IBike> =
    [
        {
            modelName: "carModelName",
            numberOfDoors: 4,
            isDropTop: true,
        },
        {
            modelName: "bikeModelName",
            hasDynamo: true
        }
    ]

If at a later point you need to determine whether an IVehicle is actually an IBike or ICar, you can utilize user-defined type guards for this purpose.

function isBike(vehicle: IVehicle): vehicle is IBike {
    return (<IBike>vehicle).hasDynamo !== undefined;
}

function isCar(vehicle: IVehicle): vehicle is ICar {
    return (<ICar>vehicle).numberOfDoors !== undefined;
}

function log(vehicle: IVehicle) {
    if (isBike(vehicle)) {
        // TypeScript compiler recognizes vehicle as IBike
        console.log(vehicle.hasDynamo);
    } else if (isCar(vehicle)) {
        // TypeScript compiler recognizes vehicle as ICar
        console.log(vehicle.numberOfDoors);
    } else {
        console.log(vehicle.modelName);
    }
}

For more information on this topic, refer to the User-Defined Type Guards section in the handbook.

To see a complete working example of the code provided, visit the playground here.

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

The problem encountered with the Enzyme mount API is a TypeError where it is unable to read the property 'find' of an undefined variable

After converting my component to a stateless one, I started encountering an error that says: TypeError: Cannot read property 'find' of undefined Previously, my tests were running smoothly before the switch. As far as I know, you can test functio ...

Can you explain the distinctions among <Div>, <StyledDiv>, and <Box sx={...}> within the MUI framework?

When exploring the MUI documentation, I came across a table of benchmark cases that can be found here. However, the differences between the various cases are not clear to me. Can someone please explain these variances with real examples for the following: ...

Using Vue Js directive to implement a Select2 component

I've been exploring the example of the Vue.js wrapper component and trying to customize it to use a v-select2 directive on a standard select box, rather than creating templates or components for each one. You can view my implementation in this JS Bin ...

Locating the elusive sequence number within a document

Greetings, I am currently trying to locate a missing number within an xml file but seem to be encountering some challenges. Any suggestions or ideas would be greatly appreciated. Example The file contains an <a> tag with various ids such as page-1, ...

Exploring the concept of next middle-ware within the realm of Express.js and Sail.js controllers

Currently, I am utilizing sails.js framework which is constructed on top of express.js. Within my routes.js file, I have defined a route as shown below: '/account/login': { controller : 'Session', action : 'l ...

Steps to ensure a dropdown menu remains expanded when its nested menu is selected

Check out this dropdown list here, but the issue arises when clicking on a nested menu item such as "Books Registration". Once that page loads, the dropdown menu collapses like shown here. Here's a snippet of the dropdown code: <ul class="nav nav- ...

Retrieve the JSON response from the server and store it in variables using jQuery's AJAX function with the `done

I am trying to retrieve a JSON response from the server upon clicking a button and then parse it into a div. However, I am struggling with how to accomplish this. <button type="submit" id="btPay" name="btPay"> Go for Pay ...

What is the best way to convert a Date into the JSON format before sending it to the database?

I'm currently delving into backend development with Node.js, and I am in the process of connecting my backend to a MongoDB. Specifically, I am working on creating a User object that includes Birth Date as one of its properties. However, I am strugglin ...

issue with duplicating DOM element using function

My situation is unique from the one described in this post. The code mentioned there is not functioning as expected when clicking the clone button. I have even provided a video explanation of how that code works. Unfortunately, I haven't received any ...

Creating an AJAX data form in a JSP scenario

I want to correctly set up the data parameter for the ajax call. <script type="text/javascript"> $(document).ready(function() { $('#call').click(function () { $.ajax({ type: "post", ...

Display exclusively the chosen option from the dropdown menu

I am facing an issue with the select input on my webpage. Whenever I try to print the page, it prints all the options of the select instead of just the one that is selected. Can someone please guide me on how to modify it so that only the selected option ...

Activate numerous progress bars to animate as the user scrolls beyond the designated anchor point

Check out my website here: I've spent a lot of time working on this site, but I've hit a roadblock when it comes to animating the skill bars. I still want them to animate as users scroll past a certain point, but I'm struggling to figure it ...

Refreshing Dropotron Data with jQuery

I'm struggling to find a solution for refreshing the <ul> and <li> elements after the page has already loaded. My <li> element is updated with Ajax data, but despite using jQuery to manipulate the DOM, the changes are not reflected ...

Guide to switching between 3 classes with mouseover using JavaScript

Currently, I am dealing with an unordered list that contains 4 items. The goal is to have the list grow to 100% of its width when hovered over, while all 'noun hovered li' items should shrink to a width of 0%. Once the cursor leaves, everything s ...

Issues with aligning center vertically and horizontally using flexbox are causing unexpected behavior

Understanding the basic concepts of centering a flex container using justify-content:center and align-items: center, I am facing an alignment issue with my box. Can anyone help me with this? This is what I have attempted so far: <template> <di ...

"Utilizing Typescript's keyof operator on its own

I'm grappling with the challenge of creating a type that can utilize the typeof its own keys, but I'm hitting a roadblock. Below is a simplified version of what I'm attempting to achieve: type SpecialType = Record<string, (getter: <K e ...

Express always correlates the HTTP path with the most recently configured route

Recently, I encountered a strange issue with my Express routes configuration. It seems that no matter which path I request from the server, only the callback for the "/admin" route is being invoked. To shed some light on how routes are set up in my main N ...

Steps for incorporating a type declaration for an array of objects in a React application with TypeScript

How can I specify the type for an array of objects in React using TypeScript? Here is the code snippet: const SomeComponent = (item: string, children: any) => { //some logic } In this code, you can see that I am currently using 'any' as ...

Issue with VueJS where the datalist input does not reset the value

I am currently working on a Vue component that scans QR codes and adds information to a database upon successful scanning. The scanning process works perfectly fine. However, after successfully sending the data, I need to clear the input field in my datali ...

Instructions for including a script and stylesheet exclusively on a single page of a website

I need to incorporate these two lines onto a single page of my website: <script src="//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.js"></script> As well as <link href="//cdnjs.cloudflare.com/ajax/libs/OwlCa ...