Is it feasible to securely remove an item from an array within an object without the need for any assertions in a single function?

My interest in this matter stems from curiosity. The title may be a bit complex, so let's simplify it with an example:

type ObjType = { items: Array<{ id: number }>; sth: number };
const obj: ObjType = {
  sth: 3,
  items: [{ id: 1 }, { id: 2 }, { id: 3 }]
};

Suppose I want to delete an item by its id from obj.items, for instance the id 2, and return the updated object without mutating the original one. Achieving this in JavaScript is straightforward, but I aim to maintain type safety using TypeScript as well. Here is what I came up with:

function removeItemFromArray<S, A extends { id: number }>(
  obj: S,
  field: keyof S,
  array: A[],
  valueToCompare: number
): S {
  return {
    ...obj,
    [field]: array.filter(i => i.id !== valueToCompare)
  };
}

The presence of the array parameter might seem redundant since it will always refer to obj[field]. However, if we were to simply use obj[field], there would be no guarantee that it actually represents an array. So, how can we ensure that obj[field] indeed contains an array of objects with an id property? My intuition tells me that conditional types hold the key to solving this puzzle, though I'm still working on unraveling the specifics.

Answer №1

To achieve the desired outcome, it is important to ensure that the obj object has the correct structure:

function removeFromArray<S extends { [f in F]: { id: number }[] }, F extends keyof S>(
  obj: S,
  field: F,
  valueToRemove: number
): S {
  return {
    ...obj,
    [field]: obj[field].filter(i => i.id !== valueToRemove)
  };
}

const obj = {
  something: 3,
  elements: [{ id: 1 }, { id: 2 }, { id: 3 }]
};

removeFromArray(obj, "elements", 2);

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

Steps for Adding a JSON Array into an Object in Angular

Here is a JSON Array that I have: 0: {name: "Jan", value: 12} 1: {name: "Mar", value: 14} 2: {name: "Feb", value: 11} 3: {name: "Apr", value: 10} 4: {name: "May", value: 14} 5: {name: "Jun", value ...

Tips for updating a JSON object value in Node.js

Storing a JSON object in a JSON file is important for passing data during an API call. To update the object, replace "it-goes-here" with the following {} block. Newly updated data: { "parenturl":"xxx.com", "user ...

It seems that every time you save data in Angular, the local storage array gets overwritten

While using Angular, I encountered an issue with saving to local storage. The code works fine for saving items initially, but on refreshing the page and trying to add more objects to the local storage array, it overwrites instead of appending. Can you help ...

The cookie value is blank once after moving to the second page

I'm facing an issue with 2 domains where performing an action on the first domain results in setting a cookie that should be accessible on both domains. However, when trying to read the value of this cookie on the second domain, it appears empty. Can ...

Switching from module.exports in Javascript to Typescript format

My Node-express code currently uses module.exports to export functions. As I am converting the code to TypeScript, I need to find out how to replace module.exports in typescript. Can you help me with this? ...

Angular 11 along with RxJS does not support the combineLatest method in the specified type

Hey there, I'm currently working on utilizing the combineLatest operator to merge two streams in Angular, but I keep encountering an error message stating that "combineLatest does not exist on type". I've attempted to move the code into a .pipe() ...

Snackbar and RTK Query update trigger the error message: "Warning: Cannot update during an existing state transition."

I've built a basic ToDos application that communicates with a NodeJS backend using RTK Query to fetch data, update state, and store cache. Everything is functioning properly as expected with the communication between the frontend and backend. Recently ...

An issue occurred with building deployments on Vercel due to a typing error

When attempting to deploy my build on Vercel, I encountered an error. The deployment works fine locally, but when trying to build it on vercel, the following error occurs: [![Type error: Type '(ref: HTMLDivElement | null) => HTMLDivElement | null&a ...

Tips for bypassing the 'server-only' restrictions when executing commands from the command line

I have a NextJS application with a specific library that I want to ensure is only imported on the server side and not on the client side. To achieve this, I use import 'server-only'. However, I also need to use this file for a local script. The i ...

Exploring the traversal of an array of objects within Tree Node

How can I transform my data into a specific Tree Node format? Is there a method (using Typescript or jQuery) to iterate through each object and its nested children, grandchildren, and so on, and modify the structure? Current data format { "content" ...

The data in the Angular variable is not persisting

After calling this function to retrieve an array of Articles, I noticed that the data is not being saved as expected. Take a look at my console output below. GetAll() { //return this.http.get<Array<Article>>(this.cfg.SERVER); this.http.get ...

Using the original type's keys to index a mapped type

I am currently developing a function that is responsible for parsing a CSV file and returning an array of objects with specified types. Here is a snippet of the code: type KeyToTransformerLookup<T> = { [K in keyof T as T[K] extends string ? never : ...

ReactJs Error: Unable to access property value because it is undefined (trying to read '0')

I am currently attempting to retrieve and display the key-value pairs in payload from my JSON data. If the key exists in the array countTargetOptions, I want to show it in a component. However, I am encountering an error message stating Uncaught TypeError ...

Navigating through Dynamic URL Parameters with RouterLink in an Angular Application

Within my Angular 2 application, there exists a tab section where users can choose from a collection of separate yet contextually connected components. By clicking on one of these links, the corresponding component is loaded based on the routerLink definit ...

Is it possible to transform a webpack bundled javascript file into typescript source code?

Is it possible to decompile a webpack-bundled JavaScript file into TypeScript source code? I have a bundle.js file that was bundled using webpack, but the original source code files were accidentally deleted. I am hoping to reverse engineer the bundle.js ...

Discovering ways to optimize argument type declarations in TypeScript

If we consider having code structured like this: function updateById( collection: Record<string, any>[], id: number, patch: Record<string, any> ): any[] { return collection.map(item => { if (item.id === id) { return { ...

How to utilize TypeScript fetch in a TypeScript project running on node with Hardhat?

During a test in my hardhat project on VSCode, I encountered the need to retrieve the metadata object of my NFT from a specified URL. Initially, I assumed I would have to import fs to read the URL. However, while typing out the method, I impulsively opted ...

Encountering obstacles when trying to implement mongoose virtuals in a TypeScript environment

I have been exploring how to utilize virtuals in mongoose with typescript. Let's say I have an interface for defining a user. interface User { id: mongoose.ObjectId; name: string; likes: string; } Next, I define a schema for mongoose. // ...

Issue with Moment Js: Unable to change date with time zone function

Trying to convert a UTC date and time to local time ("Europe/Paris") using moment's timezone function, but encountering issues. The code I am using is: var m = moment.tz(this.startTime, 'Europe/Paris'); this.startTime = m.format("YYYY-MM-DD ...

Embedded Facebook SDK posts appearing only after performing a hard refresh

I tried to implement sharing facebook posts on my client's website following the instructions provided in the Facebook embedded post documentation. The website is built using the React NEXT.js framework. I added the SDK right after opening the body ...