I am working on creating a customized form generator that is strongly typed, and I need to configure it with options based on the model. I'm wondering if it's possible to determine the return type of a function from its arguments in TypeScript, as I may have overlooked some inference basics.
To illustrate my point, I have created a simple, synthetic (and somewhat pointless) example:
// Defining an Option type that takes an OptionName key and returns fields based on the Model
type Options<Model extends Record<string, any>, OptionName extends string = string> = {
[key in OptionName]: {
fields: {
[field in keyof Model]?: {
label: string;
};
};
};
};
// Here is a basic function that returns options and expects the return type to be based on the provided options
function useOptions<Model extends Record<string, any>>(options: Options<Model>): Options<Model, keyof typeof options> {
return options as Options<Model, keyof typeof options>;
}
Here is how you can use this function:
type Person = {
lastname: string;
firstname: string;
country: string;
};
const options: Options<Person> = {
ContactFields: {
fields: {
lastname: {
label: 'Lastname',
},
firstname: {
label: 'Firstname',
},
},
},
AddressFields: {
fields: {
country: {
label: 'Country',
},
},
},
};
// No type error is returned
const { ContactFields, AddressFields } = useOptions<Person>(options);
// No type error is returned
// Should ideally return type errors since the return type doesn't match the options
const { OptionOne, OptionTwo } = useOptions<Person>(options);
The expected return type should look like this:
type ExpectedReturnType = {
ContactFields: {
fields: {
[key in keyof Person]?: {
label: string;
};
};
};
AddressFields: {
fields: {
[key in keyof Person]?: {
label: string;
};
};
};
};
Is there a way in TypeScript to solve this issue or should I consider an alternative approach?
Thank you in advance for your insights :)