我无法从 TypeScript 和 Express 应用程序中的另一个函数中访问对象值。

huangapple go评论78阅读模式
英文:

I can't access the object value from another function in typescript and express app

问题

我正在尝试在我的应用程序中使用typescriptexpress。我编写了一个函数,希望在多个地方使用。我调用了这个函数,当我使用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&lt;ImageResultType | ResponseType&gt;

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

huangapple
  • 本文由 发表于 2023年1月5日 04:01:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75010688.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定