【问题标题】:Typescript: object key should be partial of union type key打字稿:对象键应该是联合类型键的一部分
【发布时间】:2021-09-22 11:11:13
【问题描述】:

我有一个联合类型:

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 } = {
  // ...
}

有什么想法吗?

【问题讨论】:

  • { [key in AddPaymentMachineEvents['type']]?: string } 应该可以解决问题

标签: typescript union-types


【解决方案1】:

这篇文章似乎回答了我的问题: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',
}

【讨论】:

    猜你喜欢
    • 2021-02-05
    • 2020-03-03
    • 2020-04-19
    • 2022-06-13
    • 1970-01-01
    • 2021-10-06
    • 2019-03-13
    • 1970-01-01
    • 2021-07-08
    相关资源
    最近更新 更多