Vue3+TypeScript声明string类型变量报错ts(2693),如何解决?
问题解决:Vue3+TS中声明
currentTheme变量的错误修正 错误原因
你代码里的currentTheme: string = "defaultTheme"写法错误——string是TypeScript的类型标识符,不是可直接使用的JavaScript值,你把类型当作了赋值对象,所以触发了'string' only refers to a type, but is being used as a value here.ts(2693)错误。
另外还要注意:你把mounted生命周期钩子嵌套在methods里是不符合Vue规范的,生命周期钩子需要作为组件顶级选项存在,不能放在methods中。
解决方案
方案1:适配你当前的Options API结构
在Vue3的Options API中,响应式变量必须放在data选项里,TypeScript类型可以通过自动推断或显式断言指定:
export default defineComponent({ name: 'App', // 把currentTheme放在data中声明为响应式变量 data() { return { // 方式1:TS自动推断类型为string(推荐) currentTheme: "defaultTheme", // 方式2:显式指定类型(适合需要约束更严格类型场景) // currentTheme: "defaultTheme" as string, } }, // 生命周期钩子直接作为顶级选项,不要嵌套在methods里 mounted() { // 可通过this.currentTheme访问变量 console.log(this.currentTheme) // 你的原有业务逻辑... }, // 原有方法放在单独的methods选项中 methods: { // 你的其他组件方法... } })
方案2:Vue3+TS推荐的Composition API写法
如果可以重构代码,Composition API更契合TypeScript的类型系统:
import { defineComponent, ref, onMounted } from 'vue' import { useRouter, useStore } from 'vuex' // 按需导入路由、状态管理实例 export default defineComponent({ name: 'App', setup() { // 用ref声明响应式变量,显式指定string类型 const currentTheme = ref<string>("defaultTheme") const router = useRouter() const store = useStore() onMounted(() => { // 直接通过currentTheme.value访问变量 console.log(currentTheme.value) // 你的原有业务逻辑(注意Composition API中无this,直接使用router、store实例) }) // 暴露变量给模板使用 return { currentTheme } } })
内容的提问来源于stack exchange,提问作者Kanchana Kariyawasam
相关产品推荐
相关产品推荐

