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

Type safe persist paths #292

Open
3 tasks done
biesbjerg opened this issue Mar 28, 2024 · 2 comments
Open
3 tasks done

Type safe persist paths #292

biesbjerg opened this issue Mar 28, 2024 · 2 comments
Labels
✨ enhancement New feature or request

Comments

@biesbjerg
Copy link

biesbjerg commented Mar 28, 2024

Clear and concise description of the problem

Would be nice to make paths be type safe to prevent errors.

export const usePlayerStore = defineStore("player", () => {
  return {
    keyA: true,
    keyB: true,
    keyC: {
      keyC1: true,
    },
  };
}, {
  persist: {
    paths: ["keyA", "keyb"] // oops, keyB is mis-spelled
  },
});

Suggested solution

You can do this today:

type FlattenKeys<
  T extends Record<string, unknown>,
  Key = keyof T,
> = Key extends string
  ? T[Key] extends Record<string, unknown>
    ? `${Key}.${FlattenKeys<T[Key]>}`
    : `${Key}`
  : never;

type StateKeys = FlattenKeys<ReturnType<typeof storeFn>>;

function storeFn() {
  return {
    keyA: true,
    keyB: true,
    keyC: {
      keyC1: true,
    },
  };
}

export const usePlayerStore = defineStore("player", storeFn, {
  persist: {
    paths: ["keyA", "keyb", "keyC.keyC1"] satisfies StateKeys[], // Will complain that `keyb` does not exist
  },
});

Alternative

It would be great to have this built-in to Pinia so you wouldn't have to separate the storeFn by it self to be able to get the ReturnType.

Additional context

No response

Validations

@biesbjerg biesbjerg added the ✨ enhancement New feature or request label Mar 28, 2024
@prazdevs
Copy link
Owner

This is planned someday when i get some time, maybe for v4, as i already made a package for it (see https://github.com/prazdevs/deep-pick-omit)

I'm just overworked and can't spend much time onthe project atm.

@biesbjerg
Copy link
Author

No worries — thank you for a great plugin! 😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
✨ enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants