Home > Enterprise >  Typescript merging two object with spread operator and having a resuable type
Typescript merging two object with spread operator and having a resuable type

Time:04-06

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

CodePudding user response:

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'> {}
  • Related