pinia-plugin-persistedstate
pinia-plugin-persistedstate copied to clipboard
Type safe persist paths
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.
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.
No worries — thank you for a great plugin! 😊
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).