Pinia unwrapping ref in class, causing type mismatch #2192
-
demo repository: https://github.com/JerryChan31/pinia-type-issue I defined two classes as below: import { ref, Ref } from "vue"
export class Chip {
model: Ref<string> = ref('amd')
}
export class Robot {
name: string = 'ET'
chip: Chip = new Chip()
} and put its instance in pinia store: export const useRobotStore = defineStore('robot', () => {
const currentRobot = ref(new Robot())
return {
currentRobot
}
}) Then, I define a composable, whice take a 'Chip' instance as params: const useSayChipModel = (chip: Chip) => {
const say = () => {
console.log(chip.model)
}
return {
say
}
} The questions is, when I try to pass the chip instance to this composable, ts checking reports error: useSayChipModel(robotStore.currentRobot.chip)
^^^^^^^^^^^^^^^^^
// Argument of type '{ model: string; }' is not assignable to parameter of type 'Chip'.
// Types of property 'model' are incompatible.ts(2345) It seems Pinia unwrapped the 'Ref' type in I tried to cast the type, adding Ref, and ts checks went silence. useSayChipModel(robotStore.currentRobot.chip as unknown as { model: Ref<string> }) So I think it's the unwrap make the difference. I would like to know how to avoid this error, would be grateful to anyone who can give me some idea~ Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I figured out the solution... The type decalaration of the composable should be: import { UnwrapNestedRefs } from 'vue';
const useSayChipModel = (chip: UnwrapNestedRefs<Chip>) => {
const say = () => {
console.log(chip.model)
}
return {
say
}
} |
Beta Was this translation helpful? Give feedback.
I figured out the solution... The type decalaration of the composable should be: