【发布时间】: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 }应该可以解决问题