zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript] Function scope in typescript

typescript in Function Scope
2023-09-14 08:59:11 时间

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