0

I have a computed property (array) which is taken from another computed property.

When trying to use map/filter/reduce/find on the property, it causes the linting error:

Property 'map' does not exist on type 'ComputedRef<any>

So how do I declare that computed property in the correct way? I'm using Vue 3 (composition api) with Typescript and Volar (for vscode).

const product = reactive({});            //<-- empty until it is loaded

const getItem = computed(() => {
  return items.map( (item:any) => {      //<-- typescript error
    return item;                   //(simplified code, returns 1 item in reality)
})

const items = computed(() => {
  return product?.items;                //<-- items array        
});

I also tried

const items = computed<any[]>(() => {

which causes the same error (on getItem function).

And this:

const items:any[] = computed<any[]>(() => {

which causes error on "items" that says Type 'ComputedRef<any>' is missing the following properties from type 'any[]': length, pop(..etc)

1 Answer 1

3

Computed refs have a value prop that allow you to access the ref's, well, value.

So you would actually use it like this:

const product = reactive({});

const getItem = computed(() => {
  return items.value.map((item:any) => {
    return item;
  });
});

const items = computed(() => {
  return product?.items;     
});
Sign up to request clarification or add additional context in comments.

5 Comments

That does work, but I thought I didn't need it when using "reactive"? This code works without using "value": const test1 = reactive({ myProp: 'okay' }); const getProp = computed(() => test1.myProp); So do I have to use ".value" if accessing an array or something that is not a primitive value?
@Galivan Sorry, I meant to say "computed refs". Only computed refs seem to require the value prop.
But why does the code snippet work then? (adding ".value" to that snippet causes error) Is it because the computed property was referencing a computed property? I can add the snippet to the question
@Galivan You aren't using the computed ref getProp, you're using the reactive value test1.
Okay great, I got it now , thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.