Considering the given categories:
type Category1 = {
label: 'category1';
attribute: string;
};
type Category2 = {
label: 'category2';
value: string;
};
type Category3 = {
label: 'category3';
attribute: number;
};
The objective is to manually construct an object with the following structure:
{
category1: {
key: 'attribute'
},
category2: {
key: 'value'
},
category3: {
key: 'attribute'
}
}
The intention is to define it in a way that automatically recognizes the allowed top-level property names (the "label" value from each type) along with the potential values for key
(any property names in that type besides "label" are valid).
This can be achieved for one type as shown below:
type AllCategories = Category1 | Category2 | Category3;
type CustomObject<T extends AllCategories> = {
[Property in T['label']]: {
key: keyof Omit<T, 'label'>;
};
};
const customizedObj: CustomObject<Category1> = {
category1: {
key: 'attribute',
},
};
This type will permit any individual ABC type. Yet, the challenge lies in enabling the object to encompass all ABC types.
The aim is to specify "category1", and when assigning its "key" value, only "attribute" should be accepted. Subsequently, adding the "category2" key to the same object must restrict the possible "key" value to just "value".
The mentioned types serve as examples; actual ones comprise numerous fields and diverse types.