I am currently working on incorporating a predefined TypeScript configuration that can be dynamically loaded into my application. The configuration is structured as shown below:
// Base object types
type Config<D> = {
fn: ({ option }: { option: D }) => any;
option: D;
};
type ConfigRecord<T extends Record<keyof T, any>> = {
[K in keyof T]: Config<T[K]> & { type: K };
};
// Helper function to type function argument
const typeConfigRecord = <T extends Record<keyof T, any>>(
map: ConfigRecord<T>
) => map;
// Actual implementation of type
const tableConfig = typeConfigRecord({
test: {
type: "test",
fn: ({ option }) => {
return option;
},
option: "test",
},
test2: {
type: "test2",
fn: ({ option }) => {
return option;
},
option: 2,
},
});
const defaultConfig = typeConfigRecord({
tester: {
type: "tester",
fn: ({ option }) => {
return option;
},
option: "test3",
},
test2: {
type: "test2",
fn: ({ option }) => {
return option;
},
option: "A"',
},
});
const configRecordMap = {
table: tableConfig,
default: defaultConfig
}
My goal is to interact with this logic using nested generic functions setup:
const dynamicLogic = <S extends keyof typeof configRecordMap>(variant: S) => {
const selectedRecord = configRecordMap[variant];
const dynamicExecute = <K extends keyof typeof selectedRecord>(type: K) => {
const config = selectedRecord[type];
return config.fn({ option: config.option }); // Issue
}
}
In addition, I have included the following typing for the configRecordMap:
type ConfigRecordMap<T extends Record<keyof T, any>> = {
[K in keyof T]: ConfigRecord<T[K]>;
};
const typeConfigRecordMap = <T extends Record<keyof T, any>>(
map: ConfigRecordMap<T>
) => map;
const configRecordMap = typeConfigRecordMap({
table: tableConfig,
default: defaultConfig
});
However, this results in errors where the property option
represents an intersection of all potential parameter types. How can I relate this to the config.option
object?