Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
  }
}

>Solution :

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'> {}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading