I've built a callable firebase cloud function generateReport
which returns the following object:
{
id: string,
fileName: string,
numOfRows: string,
createdOn: number
}
When I call it from my React TypeScript code using a custom reusable apiCall
function, TypeScript isn't aware of what the function returns, and throws an error when I try to access the return variables.
React Code Calling Cloud Function
function apiCall({ functionName, payload }) {
const request = httpsCallable(functions, functionName)
return request(payload)
}
const response = await apiCall({
functionName: AdminFunctions.GENERATE_REPORT, payload: {
organisationId: organisation.id,
projectId: project.id
}
})
const { id, fileName, numOfRows, createdOn } = response.data // Error occurs here
Error I get:
Property 'id'/'filename'/'numOfRows'/'createdOn' does not exist on type '{}'.
I want to keep using the generic apiCall
function. It actually exists in a separate file and is used for all of my api calls.
How can I make TypeScript comfortable with the response variables I am trying to access?
CodePudding user response:
You can specify the type of the response object when calling the apiCall function. You can do this by providing a type parameter to the function, like this:
function apiCall<T>({ functionName, payload }): T {
const request = httpsCallable(functions, functionName);
return request(payload);
}
const response = await apiCall<{
id: string;
fileName: string;
numOfRows: string;
createdOn: number;
}>({
functionName: AdminFunctions.GENERATE_REPORT,
payload: {
organisationId: organisation.id,
projectId: project.id,
},
});
const { id, fileName, numOfRows, createdOn } = response.data;
This tells TypeScript that the apiCall function will return an object with the specified structure. You can then access the properties of the returned object without any errors.