简体   繁体   English

Typescript 将两个 object 与传播运算符合并并具有可重用的类型

[英]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.我正在制作一个 function 来获取和设置一个值。 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?是否有更简单的方法允许您动态添加问号,或者这是 go 的方式? Because I want the original variables to be required in the Vars type.因为我希望 Vars 类型中需要原始变量。

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

You can use the Partial utility type您可以使用Partial实用程序类型

interface NewVars extends Partial<Vars> {}

//Or

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

See this on TS PlaygroundTS 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'> {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM