Question
How can I extract an object's properties and their generic types within a function's type annotation?
I need to be able to infer the type RequestData
, so that type propagates properly to the request
callback.
Currently when invoking this function, I have to write my request
callback with type assertions. I would like my IDE to infer the type of data
based on the Form
object being passed in.
Also, any advice on how to get rid of the any
in my example is appreciated.
Thanks!
Example
class Field<T> {
value: T;
constructor(value: T) {
this.value = value;
}
}
class Form {
// Object containing all Field objects in 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; // Extract value stored in every 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) => {
// data should be of type { [K in keyof typeof myForm.fields]: typeof myForm.fields[K] }
// which in this case is { name: string; age: number | null }
// Actual type is unknown
});