In Typescript, what is the antonym of "Choose"?

I'm attempting to create a custom type that can remove specific properties from an object, unlike the Pick utility.

The desired functionality is as follows:

type ObjectType = { 
    key1: number, 
    key2: string, 
    key3: boolean, 
    key4: number[] 
}

let obj: Remove<ObjectType, 'key2' | 'key4'>

In this scenario, the type of obj should be: { key1: number, key3: boolean }

Answer №1

In TypeScript version 3.5 and above, you can utilize the Omit helper to achieve the functionality you have described.

type ObjectType = { 
    key1: number, 
    key2: string, 
    key3: boolean, 
    key4: number[] 
}

let obj: Omit<ObjectType, 'key2' | 'key4'> // results in type { key1: number, key3: boolean }

If you are using an older version of TypeScript (>2.8), Eduard suggests a combination of Pick and Exclude.

To simplify this process, I typically create a helper type to shorten the code (this definition is directly from TS 3.5):

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

Answer №2

To remove the properties key2 and key4, you can use the following method:

type NewType<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

let myObj: NewType<MyObjectType, 'key2' | 'key4'>

Explanation:

The code Exclude<keyof T, K> will result in 'key1' | 'key3'

After applying

Pick<T, Exclude<keyof T, K>>
, you will get the desired output of { key1: number, key3: boolean }

Answer №3

One way to exclude a specific property from an interface is by using the 'Omit' utility type.

import { Omit } from "utility-types"

interface IHouse {
    rooms: number 
    gardenSize: number
    toilets: number
}

type Appartment = Omit<IHouse, "gardenSize">

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

Is it possible to invoke a component's function within the click function of a Chartjs chart?

How do I trigger a function in my Component from an onclick event in my chart.js? export class ReportesComponent implements OnInit { constructor(public _router: Router, private data: ReporteService) {} this.chart = new Chart('myChart', { ...

Different outputs based on input in Typescript

Looking for some help with my class method. Here is the current implementation: handleTab<B extends boolean = false>(getIndex?: B): B extends true ? number : string { return getIndex ? 1 : ''; } Encountering an error message that s ...

When using Typescript, you may encounter the error message "Declaration file for module 'xmlhttprequest' not found."

When trying to use the following code on Node: import { XMLHttpRequest } from 'xmlhttprequest'; I encountered the following error while compiling with tsc: index.ts|4 col 32 error| 7016[QF available]: Could not find a declaration file for mo ...

The type 'never' does not have a property named 'map'

Whenever I try to make an axios get request within a next.js getServerSideProps function, I encounter a persistent TypeScript error underline on the map method. Despite troubleshooting extensively, I have not been able to resolve it. The request successf ...

What strategies can be used to manage Error return types in Typescript?

I have a situation where I need to handle either an object of type Person or an Error being returned by a function. My goal is to read the values of keys in the returned object only if it's not an Error. The code snippet below throws an error on the ...

Enhance your React Typescript High Order Component by incorporating additional properties and implementing them

I am in the process of creating a React HOC with specific requirements: It should take a component as input, modify the hidden property (or add it if necessary), and then return the updated component The rendered component should not display anything whe ...

React-snap causing trouble with Firebase

I'm having trouble loading items from firebase on my homepage and I keep running into an error. Does anyone have any advice on how to fix this? I've been following the instructions on https://github.com/stereobooster/react-snap and here is how ...

What is the most efficient approach to handle the next state after calling setState in react with immer?

Using Typescript, React, and Immer, I have set up a state management system to save profiles with multiple options. My goal is to ensure that the active profile has the correct option data before saving it. const { updateProfileList, getProfile } = useProf ...

Calculating numbers with Math.ceil will result in an increase of 1

After using Math.ceil, one value was rounded up to 50 and the other to 80. However, when I added these two values together, the result unexpectedly turned out to be 131. console.log(Math.ceil(e.currentTarget.clientHeight) // 50 console.log(Math.ceil(e.cu ...

I am in the process of transitioning my JSX website to TSX and am struggling to figure out the proper placement of my type definitions

As the title suggests, I am in the process of migrating an application that I developed using the Google Maps API for rendering maps. In this app, I display information on maps and include functionality to zoom in when a user clicks on something. The erro ...

Solving the 'never' type issue in Vue3 and TypeScript for an empty array reference

I am currently in the process of migrating a component from an old Vue project that relies solely on JavaScript to a TypeScript/Vue project, and I have encountered some obstacles along the way. <script lang="ts"> import { computed, ref } fr ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

The Jest mock is infiltrating the function logic instead of simply returning a rejected promise

The Issue at Hand I am currently working on testing the correct handling of errors when a use case function returns a rejected promise along with the appropriate status code. However, I seem to be encountering an issue where instead of getting a rejected ...

Using useState, react, and typescript, is there a way to set only the icon that has been clicked to

When I click on the FavoriteIcon inside the ExamplesCard, all the icons turn red instead of just the one that was clicked. My approach involves using useState to toggle the icon state value between true and false, as well as manipulating the style to adjus ...

Step-by-step guide on activating a button only when all form fields are validated

My very first Angular 5 project. I've gone through resources like: https://angular.io/guide/form-validation and various search results I looked up, only to realize that they are all outdated. In my form, I have several input fields such as: <for ...

What is the proper way to utilize the ES6 import feature when using a symbolic path to reference the source file?

I am seeking a deeper understanding of the ES6 import function and could use some assistance. The Situation Imagine that I have a portion of code in my application that is frequently used, so I organize all of it into a folder for convenience. Now, in t ...

Is it possible to create a Cypress report that only includes the successful test cases and excludes the failed ones?

Hello everyone, I trust you are well. Currently, I am seeking a solution to exclude failed test cases from Cypress XML report when using Junit as a reporter. The issue arises when importing test results into Jira, as failures create duplicate tests instead ...

Refreshing Components upon updates to session storage - Angular

Currently, I am in the process of developing a build-a-burger website using Angular. The ingredients and inventory need to be updated dynamically based on the selected location. Users can choose the location from a dropdown menu in the navigation bar. The ...

Error encountered while fetching client credentials in Next-Auth Credential-Provider [next-auth]

Exploring the combination of nextjs and next-auth for authentication using a credential provider has been intriguing. However, I've encountered an issue when attempting to access a protected route while logged in: [next-auth][error][client_fetch_error ...

Creating a feature that automatically determines the data type of a value using the provided key

My object type has keys that map to different types: type Value = { str: string; num: number; }; I am working on creating a universal format function: const format = <K extends keyof Value>(key: K, value: Value[K]): string => { if (key === ...