Problem with types with ts, useStorage (vueuse) and Pinia
Asked Answered
M

3

6

I'm getting a weird error in the following code: Property 'length' does not exist on type '{ [RefSymbol]: true; }'.

But when I check the type of foo in the getCount function my IDE tels me its of type Foo[]. What am I doing wrong?

import { defineStore } from 'pinia';
import { useStorage } from '@vueuse/core';

interface Foo {}

export const useFooStore = defineStore('foo', {
  state: () => ({
    foo: useStorage('foo', [] as Foo[]),
  }),
  actions: {
    getCount() {
      return this.foo.length; //Here's the error
    },
  },
});

Metameric answered 17/2, 2022 at 23:24 Comment(2)
Your code seems to show no type errors (if I provide a type for Job). Can you create a minimal example that demonstrates the problem>Sikorski
@AlexWayne That's very weird. I changed it to the minimal reproducible code that you asked for... but it looks a lot like what you wrote, without errors. My IDE isn't showing any errors, only when I try to compile the typescript it happens.Metameric
S
3

I think the return value of useStorage isn't what you think. I believe it returns a ref, of sorts, with a value property that contains the actual data being stored.

Try:

useStorage('jobs', [] as Job[]).value
Sikorski answered 18/2, 2022 at 1:45 Comment(1)
Yes it does, but that's what I need it to be. In the actions part I expect to be able to work on the value thoughMetameric
F
0

Now there is not very much info in your post but from what the error message says I'd guess the following. You are defining an object with the type

{ [RefSymbol]: true; }

but as length does not exist on your type I think an array is beeing expected for jobs?

Farcy answered 18/2, 2022 at 0:20 Comment(2)
Yes, my IDE tells me its an array of type Job... but the ts compiler thinks differentlyMetameric
My IDE isn't showing any errors, but the website isn't runningMetameric
M
0

When I prepend the line with the error with

/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-ignore
return this.foo.length; //Here used to be the error

Then it suddenly works. It's hella ugly, but it works

Metameric answered 18/2, 2022 at 10:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.