I am trying to use typescript
and express
for my app. I wrote a function that I wish to use in multiple places. I called the function, I can see the values when I use console.log
, however, I can't access the values. It is telling me that the value does not exist on the type
: Here is my code:
export const httpIUploadImage = async(req: Request, res: Response,)=>{
const fileString = req?.file?.path
if(!fileString){
return res.status(404).json('no image found');
}
const uploadResponse = await cloudinaryUpload(fileString);
const result = {
url: uploadResponse.secure_url,
publicId: uploadResponse.public_id
}
return result
}catch(err){
return res.status(500).json(err)
}
}
I used it here:
export const httpCreateCategory = async(req: Request, res: Response)=>{
}
const imageResult = await httpIUploadImage(req, res);
console.log(image)//I can see the object and the values which is {url: value, publicId: value}
const url = imageResult.url// This throws type error telling me that url does not exist
How Do I fix this?
CodePudding user response:
Because Typescript can not apply type inference for your function as you have multiple return types.
So you need to add a return type on your function definition:
type ImageResultType = {url: string, publicId: string}
export const httpIUploadImage = async(req: Request, res: Response): Promise<ImageResultType | ResponseType>
After the function call you will need to check its type with type guards
function isResult(resType: ImageResultType | ResponseType): resType is ImageResultType {
return (resType as ImageResultType).url !== undefined;
}
This way you can handle your errors better with writing an else block
if(isResult(imageResult))
imageResult.url
Also I recommend to check type inference type guards