Question
Is there a way to determine and utilize an object's properties along with their generic types within the type annotation of a function?
I am looking for a method to deduce the type RequestData
so that it can be correctly passed on to the request
callback.
At present, I find myself employing type assertions when invoking this function. It would be beneficial if my IDE could automatically infer the type of data
based on the Form
object provided.
If you have any suggestions on how to avoid using any
in my code example, kindly share them as well.
Thank you!
Example
class Field<T> {
value: T;
constructor(value: T) {
this.value = value;
}
}
class Form {
// Collection of all Field objects within this Form
fields: Record<string, Field<any>>;
constructor({ fields }: { fields: Record<string, Field<any>>; }) {
this.fields = fields;
}
}
const submit = async <Response extends unknown, RequestData extends Record<string, unknown>>(
form: Form,
request: (data: RequestData) => Promise<Response>,
): Promise<Response> => {
const fieldsAsGenerics = {} as RequestData; // Retrieve values stored in each form.field
return await request(fieldsAsGenerics);
};
const myForm = new Form({
fields: {
name: new Field<string>('Charlie'),
age: new Field<number | null>(66),
}
});
submit(myForm, async (data) => {
// The expected type for data is { [K in keyof typeof myForm.fields]: typeof myForm.fields[K] }
// which, in this instance, translates to { name: string; age: number | null }
// However, the actual type remains unknown
});
See also
- TypeScript: how to extract the generic parameter from a type?
- Pass Object Key As Generic