uni-app 编辑器对pinia的storeToRefs函数解析的类型有误

发布于 1周前 作者 eggper 来自 Uni-App

uni-app 编辑器对pinia的storeToRefs函数解析的类型有误

示例代码:

import { ref } from 'vue';  
type Skin = {  
    type: string,  
    primary: string,  
    gradientPrimary: string  
}  
export const useInit = defineStore('init', () => {  
    const AppSkin = ref<Skin>({  
        type: '',  
        primary: '',  
        gradientPrimary: ''  
    })  
    return {  
        AppSkin  
    }  
})  
import {  
        useInit  
    } from 'stores.ts'  
    import {  
        storeToRefs  
    } from 'pinia'  

const {AppSkin} = storeToRefs(useInit())  

操作步骤:

代码示例可复现

预期结果:

应正确推导类型结果

实际结果:

推导结果是错误的类型

bug描述:

对storeToRefs函数返回的数据类型解析有误

image


4 回复

应该不是storeToRefs的问题,对比compositionAPI和optionsAPI两种方式定义store,useInit().AppSkin类型不一样(optionsAPI才是正确的)


参考下这个https://ask.dcloud.net.cn/question/185148

回复 zZZ1Ma: 确实,就是HbuilderX的bug

在使用 uni-app 开发时,如果你遇到 piniastoreToRefs 函数在编辑器中类型解析有误的问题,可能是因为编辑器的类型推断或配置不正确。以下是一些可能的解决方案:

1. 确保 TypeScript 配置正确

确保你的项目中的 tsconfig.json 文件配置正确,特别是 compilerOptions 部分。以下是一个基本的配置示例:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "lib": ["dom", "esnext"],
    "types": ["@dcloudio/types", "vite/client"]
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "exclude": ["node_modules"]
}

2. 确保安装了正确的类型定义

确保你已经安装了 pinia@pinia/type 相关的类型定义:

npm install pinia @pinia/type

3. 确保编辑器支持 TypeScript

如果你使用的是 VSCode,确保你已经安装了 TypeScript 插件,并且 VSCode 的 TypeScript 版本与项目中的版本一致。

4. 检查 storeToRefs 的使用方式

确保你正确使用了 storeToRefs 函数。以下是一个示例:

import { defineStore } from 'pinia'
import { storeToRefs } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  actions: {
    increment() {
      this.count++
    },
  },
})

// 在组件中使用
import { useCounterStore } from '@/stores/counter'

const counterStore = useCounterStore()
const { count } = storeToRefs(counterStore)

5. 更新 pinia 版本

确保你使用的是最新版本的 pinia,因为旧版本可能存在类型问题:

npm update pinia

6. 检查编辑器设置

如果你使用的是 VSCode,检查 settings.json 文件,确保 typescript 相关的设置正确。例如:

{
  "typescript.tsdk": "node_modules/typescript/lib"
}

7. 使用类型断言

如果编辑器的类型推断仍然有问题,可以尝试使用类型断言来解决:

const { count } = storeToRefs(counterStore) as { count: Ref<number> }
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!