如何为NgRx动作参数定义含不定数量CustomDistribution的对象类型
解决NgRx动作参数的类型定义问题
你当前的写法错误在于CustomDistribution{}不符合TypeScript的对象类型规则,要表示包含任意数量CustomDistribution类型值的键值对对象,可以用以下两种正确方式:
方式1:使用字符串索引签名
直接在类型中定义字符串索引,明确键为任意字符串、值为CustomDistribution类型:
export const updateCustomDistributions = createAction( '[Custom Distributions] update Custom Distributions', props<{ customDistributions: { [key: string]: CustomDistribution } }>(), );
方式2:使用TypeScript内置Record工具类型
Record是TypeScript专门用于定义键值对结构的工具类型,写法更简洁直观:
export const updateCustomDistributions = createAction( '[Custom Distributions] update Custom Distributions', props<{ customDistributions: Record<string, CustomDistribution> }>(), );
这两种写法都能完美匹配你给出的示例对象:
const exampleDistributions = { right: { maxWindowsActive: 1, resize: true }, left: { maxWindowsActive: 2, resize: false } }; // 该对象类型会被自动推断为Record<string, CustomDistribution>,可直接传入动作
如果需要限制键只能是特定字符串(比如仅right/left这类固定值),可以把string换成联合类型:
type DistributionKey = 'right' | 'left' | 'top' | 'bottom'; props<{ customDistributions: Record<DistributionKey, CustomDistribution> }>()
内容的提问来源于stack exchange,提问作者Jmainol
相关产品推荐
相关产品推荐

