[Typescript] Function scope in typescript

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
      }
    })

 

posted @ 2022-11-04 16:00  Zhentiw  阅读(20)  评论(0编辑  收藏  举报