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