P
P
Peter Sergeev2022-03-22 20:05:33
typescript
Peter Sergeev, 2022-03-22 20:05:33

Is it correct to explicitly set the type when calling a function?

There is such an excerpt from vue application

setup() {
    const date = ref<Date>(new Date())
    const interval = ref<number | null>(null)

    onMounted(() => {
      interval.value = window.setInterval(() => {
        date.value = new Date()
      }, 1000)
    })

    onUnmounted(() => {
      clearInterval(interval)
    })
}


The error appears in the clearInterval(interval) function argument, and in phpstorm it sounds like this:
TS2769: No overload matches this call. Overload 1 of 2, '(intervalId: Timeout): void', gave the following error. Argument of type 'Ref' is not assignable to parameter of type 'Timeout'. Type 'Ref' is missing the following properties from type 'Timeout': hasRef, refresh, [Symbol.toPrimitive], ref, unref Overload 2 of 2, '(handle?: number | undefined): void', gave the following error . Argument of type 'Ref' is not assignable to parameter of type 'number'.


The problem was solved by explicitly specifying the type of the interval argument:
setup() {
    const date = ref<Date>(new Date())
    const interval = ref<number | null>(null)

    onMounted(() => {
      interval.value = window.setInterval(() => {
        date.value = new Date()
      }, 1000)
    })

    onUnmounted(() => {
      clearInterval(Number(interval))
    })
}


I am learning ts quite recently and have not come across this before. The question is how acceptable is such a solution and are there any alternative ways?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2022-03-22
@223606322

maybe so?
clearInterval(interval.value);
or for example

if (interval.value) {
  clearInterval(interval.value);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question