打字稿:对象键应该是联合类型键

时间:2021-07-13 11:40:03

标签: typescript union-types

我有一个联合类型:

export type AddPaymentMachineEvents =
  | { type: 'USER_PRESSES_BACK' }
  | { type: 'SET_USER_ID' }

我想构造一个键为 AddPaymentMachineEvents.type (USER_PRESSES_BACK, SET_USER_ID) 且值为字符串的对象。 此对象可以具有 AddPaymentMachineEvents.type

中所有可能的键或其中可能的键的子集

所以可能是:

// empty object
const obj = {}

// or only one key
const obj = {
  USER_PRESSES_BACK: 'string1'
}

// or all keys
const obj = {
  USER_PRESSES_BACK: 'string1',
  SET_USER_ID: 'string2',
}

到目前为止,我有这个,但它只允许对象拥有所有的键,而不是一个子集:

const obj: { [key in AddPaymentMachineEvents['type']]: string } = {
  // ...
}

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这篇文章似乎回答了我的问题:https://stackoverflow.com/a/64482301/9957187

type AddPaymentMachineEvents =
  | { type: 'USER_PRESSES_BACK' }
  | { type: 'SET_USER_ID' }

type T = { [key in AddPaymentMachineEvents['type']]?: string }

const obj: T = {} // ok

// also ok
const obj: T = {
  USER_PRESSES_BACK: 'string1'
}

// also ok
const obj: T = {
  USER_PRESSES_BACK: 'string1',
  SET_USER_ID: 'string2',
}