Store's types depending on its plugin options #2041
-
Hi 👋 Does anyone have a solution or alternative for this problem, I would like to base the type of return of my store on the plugins it implements, only the stores that have an optional property that will implement the plugin (linked to #2027). Here a stackblitz and an example code below Creating the plugin const fooPlugin = (context: PiniaPluginContext) => {
if (!context.options?.bar) { // filtering the stores that do not have the 'bar' option
return;
}
const getBar = computed(() => context.options.bar);
return {
getBar,
} as const;
}; Creating the stores const useFooStoreWithPlugin = defineStore(
'fooWithPlugin',
() => {
const example = ref(false);
return {
example,
};
},
{ bar: 'string' }
);
const useFooStore = defineStore('foo', () => {
const example = ref(true);
return {
example,
};
}); Updating pinia module declare module 'pinia' {
export interface DefineStoreOptionsBase<S, Store> {
bar?: string;
}
export interface PiniaCustomProperties {
getBar: ComputedRef<string>;
}
} Do you think there is a typescript solution to get this: const fooStoreWithPlugin = useFooStoreWithPlugin()
fooStoreWithPlugin.getBar // string
const fooStore = useFooStore()
fooStore.getBar // Property does not exist on type.. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
this might be the solution with a more complex types to deal with multiple optional stores |
Beta Was this translation helpful? Give feedback.
this might be the solution with a more complex types to deal with multiple optional stores
https://github.com/yassilah/pinia-plugin-history/blob/main/src/index.ts