简体   繁体   English

如何将 object 的部分属性键提取为联合类型?

[英]How to extract part of the properties' keys of an object as a union type?

In Typescript, I'd like to do the following:在 Typescript 中,我想做以下事情:

Typescript playground Typescript 操场

type MY_OBJECT = {
  fooA: string,
  fooB: string,
  fooD: string,
  fooE: string,
  fooF: string
}

type SOME_PROPS = Extract<keyof MY_OBJECT, "fooA" | "fooB" | "fooC">

I'd like Typescript to "know" that there's no "fooC" available on keyof MY_OBJECT and warn me about that.我希望 Typescript “知道” keyof MY_OBJECT 上没有可用的"fooC" keyof MY_OBJECT警告我。

In other words, I'd like to extract part of the properties of an object and a union type and I'd like to keep it all strongly typed.换句话说,我想提取 object 和联合类型的部分属性,并且我想保持它们都是强类型的。

For example, if I ever change fooA to fooAAA on MY_OBJECT , I'd like to know immediately that I need to fix something on that Extract<> type, since fooA would no longer exist.例如,如果我在fooA上将MY_OBJECT fooAAA我想立即知道我需要修复该Extract<>类型的某些内容,因为fooA将不再存在。

Is it possible?可能吗?

My use case: I have a Redux action that is supposed to update some of the properties of a specific object.我的用例:我有一个 Redux 操作,它应该更新特定 object 的一些属性。 So I'll be using that union type (composed by the selected property names) to type my action and make sure that the action receive only the allowed names.因此,我将使用该联合类型(由选定的属性名称组成)来键入我的操作并确保该操作仅接收允许的名称。

type MY_OBJECT = {
  fooA: string,
  fooB: string,
  fooD: string,
  fooE: string,
  fooF: string
}

type SOME_PROPS = Extract<keyof MY_OBJECT, "fooA" | "fooB">
type UPDATE_SOME_PROPS  = PayloadAction<{ name: SOME_PROPS , value: SOME_VALUE }>

Here is what I've ended up doing:这是我最终做的事情:

Typescript playground Typescript 操场

I'm using keyof Pick<> .我正在使用keyof Pick<> This way you get intellisense for the extracted properties.通过这种方式,您可以获得提取属性的智能感知。

type MY_OBJECT = {
  fooA: string,
  fooB: string,
  fooD: string,
  fooE: string,
  fooF: string
}

type SOME_PROPS = keyof Pick<MY_OBJECT, "fooA" | "fooB">
type SOME_PROPS_TEST = keyof Pick<MY_OBJECT, "fooA" | "fooB" | "fooC">

type SOME_PROPS = keyof Pick<MY_OBJECT, "fooA" | "fooB">                   // WORKS
type SOME_PROPS_TEST = keyof Pick<MY_OBJECT, "fooA" | "fooB" | "fooC">     // TRIGGERS ERROR

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

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