英文:
I can't access the object value from another function in typescript and express app
问题
我正在尝试在我的应用程序中使用typescript和express。我编写了一个函数,希望在多个地方使用。我调用了这个函数,当我使用console.log时可以看到值,但是我无法访问这些值。它告诉我该值在type上不存在。以下是我的代码:
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;
};
// 在这里使用了它:
export const httpCreateCategory = async (req: Request, res: Response) => {
  const imageResult = await httpIUploadImage(req, res);
  console.log(imageResult); // 我可以看到对象和值,即{url: value, publicId: value}
  const url = imageResult.url; // 这会抛出类型错误,告诉我url不存在
  // 如何修复这个问题?
};
如何修复这个问题?
英文:
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?
答案1
得分: 0
因为 TypeScript 无法为您的函数应用类型推断,因为您有多个返回类型。
所以您需要在函数定义中添加返回类型:
type ImageResultType = { url: string, publicId: string }
export const httpIUploadImage = async (req: Request, res: Response): Promise<ImageResultType | ResponseType>
在函数调用之后,您需要使用类型守卫来检查其类型:
function isResult(resType: ImageResultType | ResponseType): resType is ImageResultType {
  return (resType as ImageResultType).url !== undefined;
}
这样您可以更好地处理错误,编写一个 else 块:
if (isResult(imageResult))
  imageResult.url
我还建议查看类型推断和类型守卫的文档:
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论