Unique custom data type for an array of objects

My collection consists of objects that share a common structure:

type Option = {
    label: string
    value: string | number | null
}

type ElementObject = {
    id: string
    options: Option[]
}

type ElementArray = ElementObject[]

const array: ElementArray = [
    {
        id: 'cars',
        options: [
            {
                label: 'One',
                value: 1,
            },
            {
                label: 'Two',
                value: 2,
            }
        ]
    },
    {
        id: 'year',
        options: [
            {
                label: '70',
                value: '1970',
            },
            {
                label: 'Unknown',
                value: null,
            }
        ]
    }
]

Each object's options array should have values of a specific type - either number for the cars object, or string and null for the year object.

Is there a way to enforce more precise type safety than simply using a union type for the value property?

I've attempted to define a stricter type directly within the array definition, but TypeScript does not uphold this restriction as expected - it allows values of other types without raising an error:

const array: ElementArray = [
    {
        id: 'cars',
        options: [
            {
                label: 'One',
                value: 1,
            },
            {
                label: 'Two',
                value: 2,
            }
        ] as {
    label: string
    value: number
}[]
    },
    {
        id: 'year',
        options: [
            {
                label: '70',
                value: '1970',
            },
            {
                label: 'Unknown',
                value: null,
            }
        ] as {
    label: string
    value: null | string
}[]
    }
]

Answer №1

Check out this solution:

type Options<T> = {
  label: string;
  value: T;
};

type ElementObject<T> = {
  id: string;
  options: Options<T>[];
};

const anObject = [
  {
    id: 'year',
    options: [{ label: 'hello', value: '123' }],
  } as ElementObject<string | null>,
  {
    id: 'cars',
    options: [{ label: 'hi', value: 123 }],
  } as ElementObject<number>,
];

We can simplify this by automating the type inference based on the value of id, eliminating the need for explicit type declarations like as ElementObject<types>.

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

Angular2: I'm looking to customize the HTML structure for the login page and home page

There are two key elements that I need to address in my ng2 project I am looking to create distinct HTML structures for the login page and home page. Currently, my router-outlet in the app module is enclosed in a template HTML structure. However, I w ...

What is the process of creating a new array by grouping data from an existing array based on their respective IDs?

Here is the initial array object that I have: const data = [ { "order_id":"ORDCUTHIUJ", "branch_code":"MVPA", "total_amt":199500, "product_details":[ { ...

Determining the type of index to use for an interface

Imagine having an interface called Animal, with some general properties, and then either be a cat or a dog with corresponding properties. interface Dog { dog: { sound: string; } } interface Cat { cat: { lives: number; } } type CatOrDog = Cat | D ...

tips for preventing issues when the data array is empty

Here is the JSON data that I am dealing with: { "id": 43, "dataEvento": "2022-09-01T00:00:00.000+0000", "dataInvio": null, "idComunicazioneAssociata": null, "certificatoMedico" ...

The error code TS2345 indicates that the argument '{ read: typeof ElementRef; }' cannot be assigned to the parameter '{ read?: any; static: boolean; }'

Currently in the process of updating my Angular application from version 7 to version 8. Upon running ng serve, I encounter the following error: Error TS2739: Type '{}' is missing the following properties from type 'EmployeeModel': stat ...

Combining default and named exports in Rollup configuration

Currently, I am in the process of developing a Bluetooth library for Node.js which will be utilizing TypeScript and Rollup. My goal is to allow users to import components from my library in various ways. import Sblendid from "@sblendid/sblendid"; import S ...

forwarding within afterCallback employing nextjs-auth0

I need to handle multiple cases for redirecting users based on various fields and custom claims in the user token, which involves navigating through complex if/else blocks. Let's consider a simpler example where I want to redirect the user to /email- ...

I'm looking for a sample of RadPieChart for nativescript + angular. Can anyone help me out?

I'm currently working on a multi-platform application that requires a PieChart to be displayed on the main screen. Can someone point me to a comprehensive example of how to implement this? I have tried following this guide and modifying it according ...

What could be causing the Properties Array to come back as undefined?

When attempting to add an item to an array stored in the properties, I am encountering an error: "Cannot read properties of undefined (reading 'value')." Within the props, the following interfaces are defined: ILinkItemProps.ts export interface ...

I encountered an error with Firebase when attempting to run functions on my local machine

Encountering a Firebase error when running the function locally using emulator in CLI $ firebase emulators:start --only functions Initiating emulators: ["functions"] functions: Using node@8 from host. functions: Emulator started at http://localhost:50 ...

Leveraging the power of React's callback ref in conjunction with a

I'm currently working on updating our Checkbox react component to support the indeterminate state while also making sure it properly forwards refs. The existing checkbox component already uses a callback ref internally to handle the indeterminate prop ...

Angular2: Promise Rejection: Quotes cannot be used for evaluation in this component

I'm currently working on a component in Angular that includes an input parameter: import {Component, Input} from '@angular/core'; @Component({ selector: 'comment', template: ` <div class="col-lg-6 col-md-6 ...

AOT compile error due to Angular interpolation syntax

I am facing an issue while compiling my application. The AOT compiler is showing an error related to Angular interpolation in an Angular 2 form: Property 'address' does not exist on type 'FirebaseObjectObservable'. Here's a sn ...

Can you merge two TypeScript objects with identical keys but different values?

These TypeScript objects have identical keys but different properties. My goal is to merge the properties from one object onto the other. interface Stat<T, V> { name: string; description: string; formatValue: (params: { value: V; item: T }) =&g ...

typescriptUsing redux: prevent parent component from accessing redux props

I'm currently using redux and typescript in my webapp project. What's the best approach for defining props in a component that receives redux-actions through @connect, as well as props from its parent? // mychild.tsx export namespace MyChildCom ...

Tips for incorporating Extract<T, U> with a nested variant?

I've encountered an issue with generated types. A particular API is providing me with two types, and I want to create distinct aliases for each. In TypeScript, we can utilize Extract<> to assist with this: type Add = { type: 'add' ...

Cypress terminal issue: Cannot find property in 'cy & CyEventEmitter' type

Tech stack: Angular v15 and Cypress V12 Despite successful runs of my component and end-to-end tests, I encounter peculiar terminal errors while running the tests. The issue could potentially stem from my Cypress configuration for shared commands. Here ...

Property element does not exist in this basic TypeScript project

I'm diving into my initial TypeScript project and encountering an issue with the "style". I attempted to utilize style!, create an if(changeBackgroundColor){}, but without success. let changeBackgroundColor = document.querySelectorAll('[data-styl ...

Exploring Local Gems with Google Places API in Ionic 2

I recently integrated the Google Maps API into my app and now I am looking to incorporate Google Places as well. I have managed to successfully implement Geolocation, but I am facing difficulties when trying to perform a nearby search for "supermarkets" in ...

The issue TS2305 arises when trying to access the member 'getRepositoryToken' from the module "@nestjs/typeorm" which is not exported

Recently, I've been exploring the world of Nestjs and TypeOrm packages, but I've stumbled upon a series of TS errors that have left me perplexed. While I've managed to resolve many of them, there's one persistent error that continues t ...