pinia-plugin-persistedstate icon indicating copy to clipboard operation
pinia-plugin-persistedstate copied to clipboard

Type safe persist paths

Open biesbjerg opened this issue 1 year ago • 2 comments

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

  • [X] Follow our Code of Conduct
  • [X] Read the Contributing Guide.
  • [X] Check that there isn't already an issue that request the same feature to avoid creating a duplicate.

biesbjerg avatar Mar 28 '24 11:03 biesbjerg

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.

prazdevs avatar Mar 28 '24 11:03 prazdevs

No worries — thank you for a great plugin! 😊

biesbjerg avatar Mar 28 '24 11:03 biesbjerg

Closing this for now as it's soon coming in v4. Current API is type inference but not forced (you get autocompletion for possible values, but no error if using potentially invalid values).

prazdevs avatar Aug 28 '24 18:08 prazdevs