首页 > 其他分享 >[Typescript] Function scope in typescript

[Typescript] Function scope in typescript

时间:2022-11-04 16:15:15浏览次数:66  
标签:Function function typescript ... text state scope data

We have the following code which has compile error:

  async function readData(event?: Event | unknown): Promise<void> {
    // ...
    let text: string | undefined
    // ...

    if (!text) return
    setData((state) => ({ ...state, data: text })) // Typescript doesn't compile because text is still `string | undefined`
  }

 

Main reason is about function scope, text is defined in readData function, and we try to use it in another function scope (state) => ({ ...state, data: text }) , because two different function scopes, therefore text remains type string | undefined

 

Solutions to resolve this issue:

  1. Move to readData scope
    if (!clipboardText) return
    const data = clipboardText // move it here
    setClipboardData((state) => ({ ...state, data })) 

 

  2. Move to arrow function scope
    setData((state) => {
      if (!text) return state;
      return {
        ...state,
        data: text
      }
    })

 

标签:Function,function,typescript,...,text,state,scope,data
From: https://www.cnblogs.com/Answer1215/p/16858165.html

相关文章