Nuxt2+TypeScript项目添加props后访问data属性出现TS报错如何解决
问题原因
这是Vue 2.x 使用Vue.extend搭配TypeScript时的已知类型推导缺陷,当组件配置项中同时存在props、data、computed时,TS的类型推断会错误识别this上挂载的属性顺序,把data返回的form对象误判为函数或计算属性类型,因此抛出属性不存在的报错。
解决方案
- 调整组件配置项的顺序
Vue.extend的类型推导对配置项的顺序非常敏感,把data选项放到props和computed的前面,绝大多数情况下可以修复推导错误。
export default Vue.extend({ name: 'MyComponent', // data放在最前面 data: () => ({ form: { address: null, city: null, postalCode: null, latitude: null, longitude: null } }), props: { someProp: String }, computed: { isLatitudeValid() { return this.form.latitude ? this.form.latitude >= -90 && this.form.latitude <= 90 : null; } } });
- 显式标注
data的返回类型
给data返回的对象定义明确的TS类型,避免自动推导出错:
interface Form { address: null | string; city: null | string; postalCode: null | string; latitude: null | number; longitude: null | number; } export default Vue.extend({ name: 'MyComponent', props: { someProp: String }, // 显式标注data返回值类型 data: (): { form: Form } => ({ form: { address: null, city: null, postalCode: null, latitude: null, longitude: null } }), computed: { isLatitudeValid() { return this.form.latitude ? this.form.latitude >= -90 && this.form.latitude <= 90 : null; } } });
- 替换编辑器插件
如果当前使用的是Vetur插件,可以替换为Vue官方维护的Volar插件,Volar对Vue 2的TS类型推导支持远优于Vetur,可以从根源避免这类推导错误。
内容的提问来源于stack exchange,提问作者mr.mams
相关产品推荐
相关产品推荐

