Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
Typescript merging two object with spread operator and having a resuable type

Hopefully this is a simple enough question but I am having trouble figuring out how to word it in the title. I was making a function that gets and sets a value. And for the setting of the value I basically have to rewrite the initial type but with a question mark next to it because I will be automatically merging the current variables with the new ones.

Is there a simpler approach that allow you to dynamically add the question mark to this or is this the way to go about it? Because I want the original variables to be required in the Vars type.

So a simple example like:

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
  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use the Partial utility type

interface NewVars extends Partial<Vars> {}

//Or

const set = (newVars: Partial<Vars>) => {...}

See this on TS Playground

If you only want to add ? to certain values, just intersect the partial of the optional keys and required keys.

type PickOptional<T extends Record<any, any>, Opt extends string> = Partial<Pick<T, Opt>> & Omit<T, Opt>

// or doing the inverse
type PickRequired<T extends Record<any, any>, Req extends string> = Required<Pick<T, Req>> & Omit<T, Req>

interface NewVars extends PickOptional<Vars, 'a'> {}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!