简体   繁体   English

类型 void 上不存在属性

[英]Property does not exist on type void

I am writing a hook to make a post request that returns two properties, sessionId and sessionData .我正在编写一个钩子来发出一个返回两个属性sessionIdsessionData的 post 请求。 I am using this hook in a component.我在一个组件中使用这个钩子。 My hook looks like this.我的钩子看起来像这样。

export const createOrder = async () => {
  try {
    const response = await postWithToken(API_ROUTES.PAYMENT_SESSION, token || '', 
    testObject)
    console.log("FROM HOOK", response)
    return response
    } catch (err: any) {
      console.log(err)
    }
  }

And my component look like this我的组件看起来像这样

const myComponent = () => {
  useEffect(() => {
    createOrder().then(data => {
      console.log("Session Data",data.sessionData)
      console.log("FROM PAGE", data)
    })
  }, [])

  return (
    <div />
  )
}

When I try to access data.sessionData on the component I get the error that sessionDta does not exist on type void.当我尝试访问组件上的 data.sessionData 时,我收到错误消息,指出 sessionDta 在类型 void 上不存在。 But If I check the logs on the console I get the same object on the component and on the hook.但是,如果我检查控制台上的日志,我会在组件和挂钩上得到相同的 object。 Also If I check on my component the typeof data I get an object.此外,如果我检查我的组件的 typeof 数据,我会得到一个 object。

Why I am getting this error?为什么我会收到此错误?

You don't return anything from your catch block, so the return type of your function is Promise<WhateverTheTypeOfResponseIs | void>您不会从 catch 块中返回任何内容,因此 function 的返回类型是Promise<WhateverTheTypeOfResponseIs | void> Promise<WhateverTheTypeOfResponseIs | void> (NB async functions implicitly return a Promise, and if your postWithToken function doesn't return anything then it's just Promise<void> ), depending on which code path happens. Promise<WhateverTheTypeOfResponseIs | void> (NB async函数隐式返回 Promise,如果您的postWithToken function 没有返回任何内容,那么它只是Promise<void> ),具体取决于发生的代码路径。

In the future you can avoid unpleasant and slightly problematic to debug issues like this by giving your functions an explicit return type and in this case the compiler will let you know that your expectation was violated:将来,您可以通过为您的函数提供明确的返回类型来避免调试此类问题时出现不愉快和轻微的问题,在这种情况下,编译器会告诉您您的期望被违反了:

const postWithToken = async (route: string, token: string, obj: any): Promise<boolean> => {
  try {
    const resp = await fetch(
      route,
      { 
        method: 'POST',
        body: JSON.stringify(Object.assign(obj, { token }))
      },
    )
    return Boolean(resp.status < 400 && resp.status >= 200)
  } catch (err) {
    console.error(err)
    return false
  }
}

const API_ROUTES = {
    PAYMENT_SESSION: 'whatever'
}

const testObject = {
  token: ''
}

const token = ''

const createOrder = async (): Promise<boolean> => { // <-- squiggles
  try {
    const response = await postWithToken(API_ROUTES.PAYMENT_SESSION, token || '', 
    testObject)
    console.log("FROM HOOK", response)
    return response
  } catch (err: any) {
    console.log(err)
  }
}

Playground 操场

The types in the example I created may be different (you'll need to sub with the actual types from your code) but you should get the idea.我创建的示例中的类型可能不同(您需要使用代码中的实际类型进行细分),但您应该明白这一点。 You can fix this by any of the following:您可以通过以下任何方式解决此问题:

  1. Explicitly return something of the correct type from the catch block.从 catch 块中显式返回正确类型的内容。
  2. Change your return type to Promise<CorrectType | undefined>将您的返回类型更改为Promise<CorrectType | undefined> Promise<CorrectType | undefined> . Promise<CorrectType | undefined>
  3. Move the error handling to the caller as suggested by goto1 in the comments.按照注释中 goto1 的建议,将错误处理移至调用者。

Also note that as goto1 points out in the comments on the question, your hook isn't actually a hook (which is fine, but be careful of terminology).另请注意,正如 goto1 在对问题的评论中指出的那样,您的钩子实际上并不是一个钩子(这很好,但要注意术语)。

This sounds like a TypeScript issue, so I suggest to provide the proper return type for your createOrder function.这听起来像是TypeScript问题,所以我建议为您的createOrder function 提供正确的返回类型。

// Use the official type for SessionData, if you have it available,
// otherwise create a new type that properly matches its shape
type CreateOrderResult = {
  sessionData: SessionData;
}

// No need for `async/await` here, just return the `postWithToken`
// and handle errors inside your component
export const createOrder = (): Promise<CreateOrderResult> => {
  // ...
  return postWithToken(
    API_ROUTES.PAYMENT_SESSION, 
    token || '',
    testObject
  )
}

// MyComponent.tsx
const MyComponent = () => {
  useEffect(() => {
    createOrder()
      .then(data => console.log(data.sessionData))
      .catch(error => /* handle errors appropriately */)
  }, [])
}

open tsconfig.json file and change打开 tsconfig.json 文件并更改

"strict": true, “严格”:真实,

into进入

"strict": false, “严格”:假的,

this usually works for me这通常对我有用

check out https://v2.vuejs.org/v2/guide/typescript.html for more information查看https://v2.vuejs.org/v2/guide/typescript.html了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型&#39;void&#39;上不存在属性&#39;sendEmailVerification&#39; - Property 'sendEmailVerification' does not exist on type 'void' “void”类型上不存在属性“forEach” - Property 'forEach' does not exist on type 'void' 类型“void”SVELTE 上不存在属性“then” - property 'then' does not exist on type 'void' SVELTE 'void'类型上不存在属性'管道' Angular 9 - Property 'pipe' does not exist on type 'void' Angular 9 角度2中的类型&#39;void&#39;上不存在属性&#39;subscribe&#39; - Property 'subscribe' does not exist on type 'void' in angular 2 类型&#39;void |上不存在typescript属性&#39;property&#39; ISample - Typescript property 'property' does not exist on type 'void | ISample 类型上不存在属性`data`<void> | AxiosHttpResponse<any> - Property `data` does not exist on Type <void> | AxiosHttpResponse<any> msal typescript 错误属性 'accessToken' 不存在于类型 'void | 令牌响应' - msal typescript error Property 'accessToken' does not exist on type 'void | TokenResponse' 在Angular2 +中,类型&#39;()=&gt; void&#39;上不存在属性&#39;nativeElement&#39; - Property 'nativeElement' does not exist on type '() => void' in Angular2+ 类型&#39;($ router:any)=&gt; void&#39;上不存在属性&#39;$ routeConfig&#39; - Property '$routeConfig' does not exist on type '($router: any) => void'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM