Combining two objects in Typescript using the spread operator and creating a reusable type

Is there a more streamlined way to dynamically add a question mark to a variable type in TypeScript, or is the approach of rewriting the type with a question mark the best way to achieve this? I'm looking to ensure that the original variables remain required in the type while also accommodating the addition of new variables.

For example, consider the following scenario:

interface Vars {
  a: number
  b: number
}

interface NewVars {
  a?: number
  b?: number
}

const createVars = () => {
  let vars: Vars = {
    a: 1,
    b: 2
  }

  const get = () => vars

  const set = (newVars: NewVars) => {
    vars = {...vars, ...newVars}
  }

  return { get, set }
}

Answer №1

To utilize the Partial utility type, you can follow these examples:

interface UpdatedVars extends Partial<Vars> {}

//Alternatively

const update = (updatedVars: Partial<Vars>) => {...}

Check this out on TS Playground

If you specifically want to add ? to select values, you can intersect the partial of the optional keys and required keys as shown here:

type PickOptionalKeys<T extends Record<any, any>, OptKeys extends string> = Partial<Pick<T, OptKeys>> & Omit<T, OptKeys>

//or take the opposite approach
type PickRequiredKeys<T extends Record<any, any>, ReqKeys extends string> = Required<Pick<T, ReqKeys>> & Omit<T, ReqKeys>

interface UpdatedVars extends PickOptionalKeys<Vars, 'a'> {}

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

Can you explain the purpose of the yarn command --prefer-offline?

After installing an npm package like react for the first time using yarn add react I noticed that the .yarn-cache folder contains many files. I assume this is where yarn stores the local cache, so when I install react again in the future, it will be pulle ...

All web resources need to be included in the web_accessible_resources manifest key

I'm encountering an issue with my Angular app. The error message on the client console reads: Denying load of chrome-extension://fiekimdgbphfmnlbiahcfdgcipcopmep/js/lib/angular/angular.min.js.map. Resources must be listed in the web_accessible_resour ...

What is the reason for the directional light shining on the box from behind?

I have inserted a DirectionalLightHelper into my code to provide lighting for a box. The light source is positioned at coordinates (2,2,1), and there are two boxes located at (0,0,0) and (3,3,3) respectively. Surprisingly, the box at (3,3,3) is also being ...

Ensure redirect is delayed until async data is fetched

Having come from the Angular world, I found it really easy and convenient to resolve data for routes. However, now that I'm using React, I'm unsure about how to achieve the same functionality. I would like to add an async data loader for my rout ...

How come I am unable to define global electron variables in my HTML when using Typescript?

I am currently working on a personal project using Electron and Typescript. Both my Main.js and Renderer.js files are in Typescript and compiled. My issue is with the "remote" variable in my template (main.html). While it works within the template, I can&a ...

Efficiently generating and managing numerous toggle buttons in Reactjs with Material-ui ToggleButtons

Currently, I am exploring the idea of designing a sidebar that incorporates a variable number of toggle buttons generated from an object containing keys and values. However, I am encountering difficulties in utilizing the "key" value to adjust the corres ...

`Troubleshooting Firebase Cloud Functions and Cloud Firestore integration`

I previously used the following Firebase Database code in a project: const getDeviceUser = admin.database().ref(`/users/${notification.to}/`).once('value'); Now, I am attempting to convert it for Firestore. My goal is to retrieve my users' ...

Sharing API data between components in Angular 5

Summary: I'm trying to retrieve data from an input field in a component form, then compare it using API services. After that, I want to take the value from the "correo" field in the form and pass it to another component. In this other component, I aim ...

Easy selector for choosing jquery css backgrounds

Here is a simple background selector that I created. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <hea ...

Having trouble with passing the callback for nested mysql queries in Async.waterfall?

I am facing an issue with my nested MySQL queries where async.waterfall is not working as expected. The second step of the waterfall is failing to append its result to the array: async.waterfall([ function(callback) { connection.query(query, function( ...

The latest update of MS CRM 2013 now includes a version number for WebResources that are of script

I came across an unusual issue in MS CRM 2013 that seems to be intentional, and I need some assistance in finding a workaround for it. The problem is that calling the getScript jQuery method from a WebResource is not possible. In CRM, a version string is ...

Tabulate the number of items in an array based on the month and

I have received JSON data with dates indicating the creation time of multiple parcels. I want to analyze this data and calculate the total number of parcels created in each month. I am new to this process and unsure about which thread on Stack Overflow can ...

Ways to modify this request in order to update the current status

How can I optimize these calls to avoid repeating the same sentence for refreshing the state? I'm not looking for a major overhaul, just some suggestions like putting this call inside a function and invoking it when needed... export const CategoriesPa ...

Ensuring JSON data protection when sending Ajax requests in JavaScript (for(;;);)

After extensive research, I have not been able to find the answer I'm looking for despite similar questions being asked. My query concerns the usage of for(;;); while(1); before an Ajax response outputs a JSON string. I am curious about how this tec ...

Generate a versatile Union type featuring a mapped property

I am currently working with different types of data enum DataTypes { Email = 'email', Checkbox = 'checkbox', } type DataTypeValues = { [DataTypes.Email]: string; [DataTypes.Checkbox]: boolean; }; type Type1<T extends DataTy ...

Using React and Redux: Sending a function to a child component, triggering it without a handler in the child component

I am experiencing difficulty sending an action through a callback in the code provided below. The action is not being sent as expected. However, if I add the Connected property to a handler like onClick, then the action is executed. How can I make my code ...

Setting the selected value of a static select menu in Angular 2 form

I'm having an issue with my Angular 2 form that includes a static select menu. <select formControlName="type" name="type"> <option value="reference">Referentie</option> <option value="name">Aanhef</option> &l ...

Adjust the overall size of the CSS baseball field

Attempting to adjust the size of the baseball field proved challenging, as it wasn't a simple task. Is there a way to achieve this effectively? Thanks, HTML - is using DIV the only method for resizing? I couldn't find a way to resize everything a ...

Activate a CSS class on click using JavaScript

Having a bit of trouble as a beginner with this. Any help would be much appreciated. This is the code in question: HTML: <div class='zone11'> <div class='book11'> <div class='cover11'></d ...

Utilizing a search bar with the option to narrow down results by category

I want to develop a search page where users can enter a keyword and get a list of results, along with the option to filter by category if necessary. I have managed to make both the input field and radio buttons work separately, but not together. So, when s ...