Struggling with types for Getters #728
-
Hey there, I want to use the composition API style and followed
import { defineStore, setActivePinia, createPinia } from "pinia";
import { computed, ComputedRef, ref, Ref } from "vue";
/*
Define a custom type for demo purposes
*/
type MyValue = { isTrue: boolean; createdAt: Date };
/*
Define the store using the composition API
*/
const useStore = defineStore("myValues", () => {
const myValues: Ref<MyValue[]> = ref([]);
const myTruthyValues: ComputedRef<MyValue[]> = computed((): MyValue[] =>
myValues.value.filter((myValue: MyValue) => myValue.isTrue));
return { myTruthyValues };
});
/*
Use the store somewhere in the project
*/
describe("Store", (): void => {
beforeEach((): void => {
setActivePinia(createPinia());
});
it("returns truthy values only", (): void => {
const myValuesStore = useStore();
expect(myValuesStore.myTruthyValues.every(myValue => myValue.isTrue)).toBeTruthy();
});
}); First: The code looks not correct to me. Since
Second: I think this is related to the first problem. But when trying to add types to the
the test throws this error
I think it is struggling with the Am I wrong? Any ideas? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
You should type things by passing a generic to const myValues = ref<MyValue[]>([]);
const myTruthyValues = computed<MyValue[]>(() => ...) Note this is not specific to Pinia, it's more about TS and generics and the exposed types for the composition API |
Beta Was this translation helpful? Give feedback.
You should type things by passing a generic to
ref
andcomputed
:Note this is not specific to Pinia, it's more about TS and generics and the exposed types for the composition API