Q
Q
QWERTY012022-03-27 18:39:06
typescript
QWERTY01, 2022-03-27 18:39:06

Why does computed composition api typing fail in vue 3?

Here is a direct indication from the documentation https://vuejs.org/guide/typescript/composition-api...

I do the same, but it does not work

<script lang="ts">
import { computed, ComputedRef, defineComponent } from 'vue'

export default defineComponent({
    const pErrorMinMessage = computed<string>(() => {
      return 'world'
    })
    const fun1 = function (val: string) {
      console.log('hello + val)
    }

  fun1(pErrorMinMessage)
})
</script>


The error text is as follows:
Argument of type 'ComputedRef' is not assignable to parameter of type 'string'.

I also found such a solution on stackoverflow
https://stackoverflow.com/questions/60856216/how-t...
did the same, but the error is the same.
<script lang="ts">
import { computed, ComputedRef, defineComponent } from 'vue'

export default defineComponent({
   const pErrorMinMessage:ComputedRef<string> = computed(():string => {
      return 'world'
    })
    const fun1 = function (val: string) {
      console.log('hello + val)
    }

  fun1(pErrorMinMessage)
})
</script>


I don't quite understand why this is happening?
PS if you put any, that is, to be like this: pErrorMinMessage:any = computed(():string => { ..... , then everything works

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2022-03-27
@QWERTY01

What do you not understand about the error text?

Argument of type 'ComputedRef' is not assignable to parameter of type 'string'.

Let me put it in the translator for you:
An argument of type 'ComputedRef' cannot be assigned to a parameter of type 'string'.

const pErrorMinMessage = computed<string>(() => {
  return 'world'
})
const fun1 = function (val: string) {
  console.log('hello' + val)
}

fun1(pErrorMinMessage.value)

W
wonderingpeanut, 2022-03-27
@wonderingpeanut

Why specify the type for computed? It's all typed. The typescript will be able to determine the type of the variable itself.
With regards to the question, both examples that you gave work correctly for me. If these examples are an exact copy of your code, then maybe the problem is a missing quote?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question