"Manipulating values in an array with a union type: a guide to setting and

I am currently working on creating an array that can have two different value types:

type Loading = {
    loading: true
}

type Loaded = {
    loading: false,
    date: string,
    value: number,
}

type Items = Loading | Loaded

const items: Items[] = []

Everything is going smoothly so far, but now I want to retrieve a value using the .find method:

const firstLoaded = items.find(({ loading }) => !loading) 

The variable firstLoaded should be of type Loaded|undefined - how can I specify this in TypeScript?

console.log(firstLoaded?.date) // doesn't work

Another question arises: how can I change a value from Loading to Loaded within the array?

const firstUnloaded = items.find(({ loading }) => loading) 
firstUnloaded.loading = false // doesn't work

Playground

Answer №1

If you're facing the first question, consider implementing type guards as a possible solution:

function checkIfLoaded(item: Items): item is Loaded {
  return (item as Loaded).loading === false;
}

if (checkIfLoaded(item)) {
   console.log(firstLoaded.date) // This should produce the desired result
}

Now onto the second inquiry, it's not as straightforward to convert directly. A better approach would be to replace the array element with another element by assigning it like this:

items[index] = transformToLoaded(items[index])

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 'path' property is not found on the 'ValidationError' type when using express-validator version 7.0.1

When utilizing express-validator 7.0.1, I encounter an issue trying to access the path field. The error message indicates that "Property 'path' does not exist on type 'ValidationError'.: import express, { Request, Response } from " ...

What is the best way to implement a Promise Function within a For loop?

Here is a function called sendEmail: public async sendEmail (log: LogMessage): Promise<void> { nodemailer.createTestAccount(async () => { return ServiceFactory.getSystemService().getNetworkPreferences().then(async (networkPreferences) => ...

Generate a fresh class instance in Typescript by using an existing class instance as the base

If I have these two classes: class MyTypeOne { constructor( public one = '', public two = '') {} } class MyTypeTwo extends MyTypeOne { constructor( one = '', two = '', public three ...

When the child component's form is marked as dirty, the parent component can access it

I have implemented a feature in my application that notifies users about pending changes on a form before they navigate away. Everything works as expected, but I have a child component with its own form that needs to be accessed by the guard to check if i ...

How to utilize the async pipe on an observable<Object> and connect it to a local variable in the HTML using Angular

Hey there! So, I have this observable called user$ which has a bunch of properties such as name, title, and address. component{ user$:Observable<User>; constructor(private userService:UserService){ this.user$ = this.userService.someMethodRet ...

Fill out FormBuilder using data from a service within Angular2

I am working with an Angular2 model that I'm filling with data from a service. My goal is to use this model to update a form (created using FormBuilder) so that users can easily edit the information. Although my current approach works, I encounter er ...

Cleaning up HTML strings in Angular may strip off attribute formatting

I've been experimenting and creating a function to dynamically generate form fields. Initially, the Angular sanitizer was removing <input> tags, so I discovered a way to work around this by bypassing the sanitation process for the HTML code stri ...

A step-by-step guide on accessing the data from an uploaded JSON file in a React application

One exciting feature is the drag and drop component that allows users to add multiple files. However, there seems to be an issue with displaying the content of a JSON file once it's added. Below is the code snippet in question: if (files?.length) ...

Is it possible that using npm link could be the root cause of the "module not

As I delve into understanding how to utilize TypeScript modules in plain JavaScript projects, it appears that I am facing a limitation when it comes to using npm linked modules. Specifically, I can successfully use a module that is npm-linked, such as &apo ...

The expandable column headers in Primeng are mysteriously missing

I'm facing an issue with my expandable row in Angular2 using Primeng2, where the column headers for the expandable columns are not displaying. Below is the code snippet of my table with expandable rows: <p-dataTable [value]="activetrucks" expanda ...

Unexpected TypeError when using Response.send()

Here is a snippet of my simple express code: const api = Router() api.post('/some-point', async (req, res, next) => { const someStuffToSend = await Promise.resolve("hello"); res.json({ someStuffToSend }); }) In my development environmen ...

Replace the default Material UI 5.0 typography theme with custom fonts on a global scale

My current challenge involves incorporating two personal fonts into the Material UI 5.0. My goal is to apply these fonts globally by overriding the theme settings. However, I have encountered issues with loading the fonts properly and modifying the typogra ...

The alignment of the first and second steps in Intro.js and Intro.js-react is off

There seems to be an issue here. Upon reloading, the initial step and pop-up appear in the upper left corner instead of the center, which is not what I anticipated based on the Intro.js official documentation. https://i.stack.imgur.com/ICiGt.png Further ...

How can I modify my Axios Post request to receive a 201 status code in order to successfully save the data?

I am facing an issue when attempting to make a POST request locally with Axios on my NodeJS front-end app to my .NET core local server. The server returns a 204 status code and the axios request returns a pending promise. How can I change this to achieve a ...

The issue with ng-select arises when the placeholder option is selected, as it incorrectly sends "NULL" instead of an empty string

When searching for inventory, users have the option to refine their search using various criteria. If a user does not select any options, ng-select interprets this as "NULL," which causes an issue because the server expects an empty string in the GET reque ...

The young one emerges within the SecurePath component temporarily

Setting up authorization in React has been a priority for me. Ensuring that users cannot access unauthorized pages within the application is crucial. To achieve this, I have created a custom component as shown below. import { ReactNode } from "react&q ...

Passing a method from a component to a service in Angular 9

Recently, I've been working on some websocket code that involves sending a message to the server and receiving a reply. The current implementation is functional, but I'm looking to refactor it by encapsulating it within a service and then callin ...

Encountering an issue when trying to download a PDF from an Angular 6 frontend using a Spring Boot API - receiving an error related to

When I directly call the Spring Boot API in the browser, it successfully creates and downloads a PDF report. However, when I try to make the same GET request from Angular 6, I encounter the following error: Here is the code snippet for the Spring Boot (Ja ...

Pressing a button that appears multiple times and is also embedded within layers

I am facing an issue where I need to interact with a button that appears multiple times on the website within nested cards. Specifically, I am trying to locate the card containing a pet named Bala, as shown in the attachment below, and click on the Detail ...

When utilizing Typescript to develop a form, it is essential to ensure that the operand of a 'delete' operator is optional, as indicated by error code ts(279

Can someone help me understand why I am encountering this error? I am currently working on a form for users to submit their email address. export const register = createAsyncThunk< User, RegisterProps, { rejectValue: ValidationErrors; } > ...