英文:
how to type an object that contains a indeterminate amount of a specific object
问题
我需要输入一个NgRx操作的参数。此参数是一个包含不确定数量特定对象的对象。最后一个对象已在接口上进行了类型定义。
export interface CustomDistribution {
maxWindowsActive: number;
resize: boolean;
}
我尝试了这个,但它不起作用:
export const updateCustomDistributions = createAction(
'[Custom Distributions] update Custom Distributions',
props<{ customDistributions: { [key: string]: CustomDistribution } }>(),
);
这是我想要获取和类型化的预期对象的示例:
distributions: {
right: {
maxWindowsActive: 1,
resize: true
},
left: {
maxWindowsActive: 2,
resize: false
}
}
英文:
I need to type the parameter of an NgRx action. This parameter is an object that contains an indeterminate number of specific object. This last object is already type on a Interface.
export interface CustomDistribution {
maxWindowsActive: number,
resize: boolean,
}
I tried this but it doesnt work:
export const updateCustomDistributions = createAction(
'[Custom Distributions] update Custom Distributions',
props<{ customDistributions: CustomDistribution{} }>(),
);
This is an example of the expected object I want to get and type:
distributions: {
right: {
maxWindowsActive: 1;
resize: true
},
left: {
maxWindowsActive: 2;
resize: false
}
}
答案1
得分: 2
你正在寻找的可能是这个:
export interface CustomDistributionGroup {
[key: string]: CustomDistribution;
// 或者如果你想允许数字键,可以这样写
// [key: number]: CustomDistribution;
// [key: string | number]: CustomDistribution; // 同时允许字符串和数字
// 感谢 @Brandon Taylor
}
如果你定义了这样的接口,那么你可以使用它来创建一个拥有无限数量的 CustomDistribution
对象的对象。但它们需要一个键,这在你的示例中并没有提供 => 这是一个无效的对象。应该像这样:
const someProps: CustomDistributionGroup = {
first: { maxWindowsActive: 1, resize: true },
second: { maxWindowsActive: 2, resize: false },
third: { maxWindowsActive: 3, resize: false },
// 等等
};
你的示例应该不起作用,我很惊讶你的IDE没有抛出错误。
英文:
What you're looking for is most likely this:
export interface CustomDistributionGroup {
[key: string]: CustomDistribution
// or like that, if you want to allow numeric keys
// [key: number]: CustomDistribution
// [key: string | number]: CustomDistribution // both string and number
// thanks @Brandon Taylor
}
If you define an interface like that, then you can use it to create an object with indefinite number of CustomDistribution
objects. But they need a key, which you didn't provide in your example => an invalid object.
This is how it should look:
const someProps: CustomDistributionGroup {
first: { maxWindowsActive: 1; resize: true },
second: { maxWindowsActive: 2; resize: false },
third: { maxWindowsActive: 3; resize: false },
// and so one
}
Your example should not work and I'm surprised your IDE is not throwing errors.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论