7
7
700Hp2022-04-03 08:36:23
JavaScript
700Hp, 2022-04-03 08:36:23

How to correctly import typescript(2698) vue 3 function?

Error code:

TS2698: Spread types may only be created from object types.
    33 |     return {
    34 |       contact,
  > 35 |       ...useHandleClick(handleClick)
       |       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    36 |     }
    37 |   }


Function code:
import { onMounted, onBeforeUnmount } from 'vue'

interface IFunction {
  (e: Event): void
}

export function useHandleClick (fn: IFunction): void {
  onMounted(() => {
    document.addEventListener('click', fn)
  })

  onBeforeUnmount(() => {
    document.removeEventListener('click', fn)
  })
}


Component code:
const handleClick = (event: Event): void => {
      const target = event.target as Element
      if (target.closest('button') || target.closest('.contact')) return
      emit('close')
    }

    // noinspection JSVoidFunctionReturnValueUsed
    return {
      ...useHandleClick(handleClick)
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
wonderingpeanut, 2022-04-03
@wonderingpeanut

https://developer.mozilla.org/en/docs/Web/JavaScript...

G
GrayHorse, 2022-04-03
@GrayHorse

Spread types may only be created from object types.

And what will spread here? undefined.
In this hook, the react ( useSomething) hook is done like this - an object is returned, whose fields are assigned to another object using the spread operator.
Examples can be found in VueUse, for example:
github.com/vueuse/.../useMemory/index.ts#L41-L53

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question