I’m using Pinia for state management in my Vue.js project with TypeScript, and I want to simplify the return type definitions for my getters. Here’s a basic example of what I have:
import { defineStore } from 'pinia';
// Define state interface
type State = {
count: number;
name: string;
}
export const useCounterStore = defineStore('counter', {
state: (): State => ({
count: 0,
name: 'Counter',
}),
getters: {
// Simple getter returning count
getCount: (state): number => {
return state.count;
},
// Getter using another getter
message: (state, getters): string => {
return `${getters.getCount} - ${state.name}`;
},
}
});
Is there a way to avoid explicitly defining the return types for each getter in Pinia, especially when one getter depends on another? I’m looking for a method to simplify the type management in my store.
To simplify the type management for getters in your Pinia store, you can use TypeScript’s utility types to infer types dynamically. Here’s how you can refactor your store code to leverage type inference and reduce explicit type definitions for each getter:
import { defineStore } from 'pinia';
type WrapInFunction<S, T> = {
[K in keyof T]: (state: S) => T[K];
};
// Define state interface
type State = {
count: number;
name: string;
}
// Define getters interface
type Getters = WrapInFunction<State, {
getCount: number;
message: string
}>
export const useCounterStore = defineStore<'counter', State, Getters>('counter', {
state: (): State => ({
count: 0,
name: 'Counter',
}),
getters: {
// Simple getter returning count
getCount: (state) => {
return state.count;
},
// Getter using another getter
message: (state, getters) => {
return `${getters.getCount} - ${state.name}`;
},
}
});