Removing a dynamic TypeScript object key was successful

In TypeScript, there is a straightforward method to clone an object:

const duplicate = {...original}

You can also clone and update properties like this:

const updatedDuplicate = {...original, property: 'value'}

For instance, consider the following code snippet:

const object = {
    'key1': 1,
    'key2': 2,
};
const keyToDelete = 'key1';
delete object[keyToDelete];

Is there a more elegant way to delete a property from an object, without resorting to the conventional delete object[keyToDelete] approach? (and obviously not using object[keyToDelete] = undefined)

Answer №1

If you're searching for a way to use computed property names and destructuring in JavaScript, this code snippet may help. Learn more here

const a = {
    'something': 1,
    'e': 2,
};

const c = 'something';

const { [c]: _, ...withoutC } = a;

In this example, the value of the property something (retrieved from the variable c) is assigned to the _ variable, while all other properties are stored in the withoutC variable. Defining c as a constant allows TypeScript to correctly infer the type of withoutC.

Answer №2

Instead of removing the property from a, you can utilize destructured assignment to create a new object without that property:

const {c, ...b} = a;

Once this is done, b will include all elements of a except for c.

If a is defined as a certain type like { c: string, d: string }, then the types of c and b will be automatically deduced as string and { d: string } respectively. However, using an Omit type, as suggested by @Nurbol Alpybayev, would be more efficient than manually specifying the types.

To avoid any naming conflicts with another variable, you can rename c using this syntax:

const {c: someOtherName, ...b} = a;

This method works well if you are aware of the property name during compilation. If the property name is not known beforehand, then TypeScript may not provide accurate assistances in determining the result type of the operation.

In such scenarios, it's better to define a as { [k: string]: number } so that delete a[c] would suffice, or you can consider using the following approach:

const exclude = <T>(map: { [k: string]: T }, omitted: string[]): { [k: string]: T } =>
  return Object.getOwnPropertyNames(a)
    .filter(k => omitted.indexOf(k) >= 0)
    .reduce((a, k) => (a[k] = map[k], a), {})
};
var b = exclude(a, ["c"]);

Answer №3

Of course! Achieving this can be done by utilizing the Omit method:

type Omission<T, K> = Extract<T, Exclude<keyof T, K>>

type RemoveFoo = Omission<{foo: 'abc', bar: 'def'}, 'foo'> // {bar: 'def'}

By the way, it just dawned on me that your question may have been directed towards extracting values rather than types. If so, you might want to explore JavaScript instead of TypeScript.

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

Unable to install vue-property-decorator

When attempting to set up Vue and TypeScript with class style using vue-property-decorator, I encountered a strange script after creating the project. I was anticipating a script like this: <script lang="ts"> import {Component, Vue} from & ...

Enhance the overall appearance of select elements across all components using Material UI's

I'm attempting to change the border color of my outlined select elements using the code below, but it's not working as expected. It seems that the border style is being inherited from the fieldset element. I've experimented with using MuiOut ...

Traversing a two-dimensional array backwards in JavaScript

I am working with an array that contains different teams: The structure looks like this: leagues = new Array( Array('Juventus'), Array('Milan'), Array('Inter')); My goal is to iterate through the array and generat ...

Leveraging Typescript Generics for limiting the input parameter of a function

Issue I have developed a Typescript package to share types between my backend node firebase cloud functions and frontend React client that accesses them. Provided below are examples of the types: interface FirstFunctionInput { x: number } interface Sec ...

Refresh the page and witness the magical transformation as the div's background-image stylish

After browsing the internet, I came across a JavaScript script that claims to change the background-image of a div every time the page refreshes. Surprisingly, it's not functioning as expected. If anyone can provide assistance, I would greatly appreci ...

In what way can you dynamically set the displayName using a higher order component?

My current struggle is setting displayName dynamically in order to improve the debugging process. Each component renders as <Component ... />, making it difficult to identify them in the codebase. While I have successfully set static displayName on e ...

What sets npm install apart from manual installation?

I've been exploring requirejs recently. I'm trying to decide between installing it using npm install requirejs or manually downloading it from the website. Are there any differences between the two methods? Are there any advantages or disadvantag ...

"Redirecting visitors based on their location using GeoIP targeting for

Is there a way to implement a code that redirects users based on their location? For example, if a user accesses the site from the United Kingdom, they should be redirected to /UK/, if from the US to /US/, and if from anywhere in the EU (excluding the UK) ...

Exploring the functionality of the Angular 7 date pipe in a more dynamic approach by incorporating it within a template literal using backticks, specifically

I have a value called changes.lastUpdatedTime.currentValue which is set to 1540460704884. I am looking to format this value using a pipe for date formatting. For example, I want to achieve something like this: {{lastUpdatedTime | date:'short'}} ...

Acquire JSON data structures using Node.js

I've been struggling to find a solution using just keywords - endless scrolling, yet all I can find are tutorials on getting data from JSON structure, rather than getting data structure from JSON. If you're unsure what my end goal is, here are s ...

Discovering the type of a generic class in TypeScript

Class B extends a generic class A, and I am trying to infer the generic type of A that B is extending. The code snippet below demonstrates this. In earlier versions of TypeScript, this worked correctly for me. However, in my current project using version ...

Angular’s ng-repeat function is behaving erratically as objects are displayed in the console

Having trouble with my ng-repeat not displaying content. Here is the code for my app.js, client controller, factory, and server controller. Everything else seems to be working fine. I can see all the console logs in Chrome and terminal, but the ng-repeat ...

Encountered a network error: A rogue token < was found in JSON at position 0 within a new Apollo

https://i.sstatic.net/D25ai.png const httpLink = createHttpLink({ uri: 'http://localhost:3090/' }) const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache() }) client.query({ query: gql` query users { ...

Utilizing REACT to extract values from deeply nested JSON structures

Currently, I am utilizing react to display information from properties stored in a nested JSON. While I can successfully render properties like 'name' and 'id' that are not nested, I encounter an issue when trying to access a nested pro ...

Revise my perspective on a modification in the backbone model

I am new to using Backbone and I am currently practicing by creating a blog using a JSON file that contains the necessary data. Everything seems to be working, although I know it might not be the best practice most of the time. However, there is one specif ...

During the build process, NextJS encountered an issue locating the constants.js module

I encountered an error while executing next build using next version ^10.2.3. I attempted to remove the node_modules and .next folders, then reinstalled dependencies with npm install && next build, but the issue persists. Error: Cannot find mod ...

Sharing data between different JavaScript files using Knockout.js

I am working with two JavaScript files named FileA.js and FileB.js. Within FileA.js, there is a function called Reports.CompanySearch.InitGrid: function InitGrid(viewModel, emptyInit) { var columns = [ { name: 'CompanyName', ...

Exploring a JSON file to generate a customized array for implementing autocomplete functionality in jQuery

I'm currently working on developing an autocomplete feature for a search bar that will display names of places in Norway. The data is being fetched from a REST API URL provided by a third party. As an example, when the input is "st" there are two res ...

Creating an outlined effect on a transparent image in a canvas: step-by-step guide

Currently, I am working on creating transparent images using canvas in HTML5 and I would like to incorporate borders into them. The issue I'm facing is that the "Stroke" property does not consider the transparency of the image and applies it as if it ...

Exploring the power of NodeJS with nested functions for conducting in-depth search

Hey there, friends! I'm currently working on a small web application using NodeJS. One of the key features in my app is a search functionality that spans across different pages. However, I have some doubts about the nested functions related to this s ...