Guide on creating a Typescript Conditional type structure for Array elements that rely on each other

In my function, I am working with an array of objects that contain an icon key. If one index in the array has a value assigned to the icon key, then another index should also have a value. If one index leaves the icon key undefined, then another index should also be undefined.

For example:

type Item = {
    title: string;
    icon?: string | undefined;
};

function Func(items: Array<Item>) {
    return items.map((item) => item);
}

Func([
    { icon: 'home', title: 'Home' },
    { icon: 'phone', title: 'Phone' },
    { icon: 'user', title: 'User' },
]); //=> no error

Func([
    { title: 'Home' },
    { title: 'Phone' },
    { title: 'User' }
]); //=> no error


Func([
    { icon: 'home', title: 'Home' },
    { icon: 'phone', title: 'Phone' },
    { title: 'User' },
]); //=> should be error, cause icon not set for `user` but set for another

Func([
    { icon: 'home', title: 'Home' },
    { title: 'Phone' },
    { title: 'User' }
]); //=> should be error, cause icon set for `home` but not set for another

Answer №1

To Update the Types to the following :


type ItemsWithoutIcon = Array<{ title: string }>;
type ItemsWithIcon = Array<{ title: string; icon: string }>;
type Items = ItemsWithIcon | ItemsWithoutIcon;

and utilize in Func like this :

function Func(items: Items) {
    return items.map((item) => item);
}

Alternatively


type ItemsWithoutIcon = { title: string };
type ItemsWithIcon = { icon: string } & ItemsWithoutIcon;
type Items = Array<ItemsWithIcon> | Array<ItemsWithoutIcon>;

This implies that the items argument should be an array of objects without the icon property. All other items should remain the same, and if an item contains the icon property, all items should also contain the icon property.

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 'zone' property is not recognized on the 'Observable<{}>' data type

I am currently following the meteor-ionic tutorial and encountering a typescript error: typescript: src/pages/details/details.ts, line: 35 Property 'zone' does not exist on type 'Observable<{}>'. This is my componen ...

Utilizing Angular2 with Webpack in Visual Studio 2015

Is there a way to utilize Visual Studio 2015 alongside Webpack and Angular2? I have successfully created an Angular2 App with VS, but now that I've added Webpack to build my app, I would like to debug all of my code using IIS Express. I want to be abl ...

Tips for adding a "Select All" feature to a dropdown list?

Currently, I have a dropdown list with a filter for IN and OUT values. The functionality is working as expected: <select class="form-select" style="max-width: 100px" [ngModel]="selectedBrand" (ngModelChange)="onChangeT ...

How can I display the values stored in an array of objects in Angular 2

I need help printing out the value of id from an array that is structured like this: locations = [ {id: '1', lat: 51.5239935252832, lng: 5.137663903579778, content: 'Kids Jungalow (5p)'}, {id: '2', lat: 51.523 ...

Discovering the object and its parent within a series of nested arrays

Is there a way to locate an object and its parent object within a nested array of unknown size using either lodash or native JavaScript? The structure of the array could resemble something like this: name: 'Submodule122'</p> I have been ...

Typescript: Determine when a property should be included depending on the value of another property

Having some difficulty with Typescript and React. Specifically, I am trying to enforce a type requirement for the interface Car where the property colorId is only required if the carColor is set to 'blue'. Otherwise, it should not be included in ...

Angular 2 implementes a loading spinner for every HTTP request made

My objective is to implement a spinner functionality whenever an HTTP request occurs in my Angular app. Essentially, I want the user to see a loading screen during these requests within my app component. The setup for my spinner component and spinner servi ...

Capturing page titles accurately for timeonsite tracker in a single-page Angular app is challenging when navigating to other pages

Implemented the timeonsite JS tracker in my Angular web application using HTML tags as shown below, <script type="text/javascript"> var Tos; (function(d, s, id, file) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementByI ...

Utilizing D3 to fetch geographic data in the form of a TopoJSON file for U.S. counties

After retrieving a set of coordinates, the goal is to use D3 to find the corresponding county from a U.S. TopoJSON file. Here is an example code snippet: navigator.geolocation.getCurrentPosition(function(position) { let coordinates: [number, number] = [p ...

The object in an Angular 11 REACTIVE FORM may be null

I am looking to incorporate a reactive form validation system in my application, and I want to display error messages based on the specific error. However, I am encountering an error that says: object is possibly 'null'. signup.component.html &l ...

Using Jimp to load a font and retrieve its Base64 representation

I am currently working in Angular with Jimp, attempting to overlay text onto an existing image. However, the image is not updating as expected. const Jimp = require('jimp') var _this = this; Jimp.read("assets/TimeLine.png").then(function ( ...

Is the return type determined by the parameter type?

I need to create an interface that can handle different types of parameters from a third-party library, which will determine the return type. The return types could also be complex types or basic types like void or null. Here is a simple example demonstra ...

What is the best method for implementing Datepicker translations in Angular?

I am looking to incorporate the DatePicker component in Angular, enabling users to select a date that can be translated based on their browser's settings. Any suggestions on how to achieve this? <mat-form-field appearance="fill"> ...

Ways to conceal an element in Angular based on the truth of one of two conditions

Is there a way to hide an element in Angular if a specific condition is true? I attempted using *ngIf="productID == category.Lane || productID == category.Val", but it did not work as expected. <label>ProductID</label> <ng-select ...

Converting a String variable to a String Literal Type in Typescript: A step-by-step guide

When working with Typescript, imagine I need to call a function that has the following signature- function foo(param: "TRUE"|"FALSE"|"NONE") Is there a way to achieve something like this- var str = runtimeString() if(str === "TRUE" | str === "FALSE" | s ...

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 ...

Using NestJS to import and inject a TypeORM repository for database operations

This is really puzzling me! I'm working on a nestjs project that uses typeorm, and the structure looks like this: + src + dal + entities login.entity.ts password.entity.ts + repositories ...

implementing firestore onsnapshotListner feature with pagination

I have a web application that needs real-time updates on a large collection of documents. However, due to the size of the collection, retrieving data without applying a limit is not feasible and inefficient. Therefore, it is crucial to implement a query li ...

NestJS TypeORM InjectRepository throwing an error: "Cannot access property 'prototype' of undefined"

Encountering an issue while trying to unit test. Here is the error message that I received: TypeError: Cannot read property 'prototype' of undefined export class UserService { constructor(@InjectRepository(User) private readonly userRepository ...

The save icon is the lone absentee in the material table

There seems to be an issue with the save icon not showing up in the editable table. The icons for outside actions are functioning properly, but the ones for inner actions are not working. Please click on the update action below: https://i.sstatic.net/Pmae ...