Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

State typing doesn't work with classes with private attributes/methods #871

Closed
hugoattal opened this issue Dec 3, 2021 · 2 comments
Closed

Comments

@hugoattal
Copy link

Reproduction

Here is a little example

import { defineStore } from "pinia";

// This is a class called "Thing" with a private attribute name
class Thing {
    private readonly name: string;

    constructor(name: string) {
        this.name = name;
    }

    getName(): string {
        return this.name;
    }
}

// This function expects a Thing as argument
function displayName(thing: Thing) {
    console.log(thing.getName());
}

// This little example works as intended
const a: Thing = new Thing("test");
displayName(a);

export const useTestStore = defineStore({
    id: `test`,
    actions: {
        getThingName() {
            // Error TS2345
            displayName(this.thing);
        }
    },
    state: () => ({
        thing: new Thing("test")
    })
});

image

Steps to reproduce the behavior

Just paste this code in WebStorm (last version)

Expected behavior

It should pass typescript compilation

Actual behavior

Typescript fire a TS2345 error because property "name" is missing

Additional information

It can be "fixed" this by forcing the type:
image

Also, it's rather a small bug, I just wanted to mention it if anyone encountered this. I ❤️ 🍍 !

@posva
Copy link
Member

posva commented Dec 3, 2021

Duplicate of vuejs/core#2981

@posva posva marked this as a duplicate of vuejs/core#2981 Dec 3, 2021
@posva
Copy link
Member

posva commented Dec 3, 2021

Pinia unwraps any property passed in the state and the resulting type is also unwrapped with UnwrapRef. For the moment, you need to manually cast it:

      displayName(this.thing as Thing)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants