typescript - VS Code Typescript 在 Vuejs 项目中给出错误“属性不存在”
问题描述
我在 Typescript 中有一个 Vuejs 项目。项目编译并运行完美,没有错误。但是 TS linter 是错误的。
我在单个组件文件中使用组件装饰器,如下所示:
//videocard.component.vue
<script lang="ts">
import Vue from 'vue';
import { Component, Prop } from 'vue-property-decorator';
import { Video } from '../interfaces/video.interface';
@Component
export default class VideoCardComponent extends Vue {
@Prop() readonly video: Video;
@Prop() readonly loading: boolean;
created(){
console.log(this.static_url); // !COMPLAINS HERE!
}
get _video(){
return this.video
}
get _loading(){
return this.loading || false;
}
}
</script>
请注意我是如何尝试注销名为static_url
. 这是有效的,因为在我的 app.ts 文件中,我将这个属性设置为:
//app.ts
Vue.prototype.static_url = (window as any).static_url;
我增加了类型,所以static_url
是 Vue 上的一个属性。像这样:
// static_url.d.ts
import Vue from 'vue';
declare module 'vue/types/vue' {
interface Vue {
static_url: string;
}
interface VueConstructor {
static_url: string
}
}
Typescript linter 不会抱怨app.ts
文件中的这个属性,但它会抱怨组件文件中的这个属性。为什么 Typescript 在组件文件中无法识别此属性?
为了完整起见,这是我的tsconfig.json
文件:
{
"compilerOptions": {
"target": "es5",
"lib": ["esnext", "dom"],
"strict": true,
"module": "es2015",
"noImplicitAny": false,
"moduleResolution": "node",
"experimentalDecorators": true,
"strictPropertyInitialization": false
},
"include": [
"assets/js/video-app/src/**/*.ts",
"assets/js/video-app/src/**/*.d.ts",
]
}
解决方案
我认为你是如此接近,我能找到的唯一问题是include
在tsconfig.json
您是否tsconfig.json
放置在您的项目之外,所以您需要有assets/js/video-app/src
路径?
通常,如果tsconfig.json
在项目中,include
应该如下所示。如果包含路径不正确,自定义类型定义将不起作用。
"include": [
"src/**/*.ts"
]
你能检查一下是否也在目录static_url.d.ts
内src
。
我做了一个 git repo 来模拟你的情况,你可以交叉检查你的设置。
推荐阅读
- html - 如何连续响应两列?在第一个文本中,在引导程序 4 中的第二个图像中
- java - 如何解决 java 8 中的“Lambdas 应该用方法引用替换”声纳问题?
- php - FCM Android 通知声音问题
- apache-kafka-streams - 关于 KTable 中抑制运算符的容错
- sql - 如何在 CASE 中执行 SELECT 语句
- java - 如何在Android的日期选择器对话框中显示所选日期的第二天日期?
- pandas - 为什么 panda 的 fillna 方法不起作用?
- java - 使用 JUnit-Tools 1.1.0 生成自动测试用例让我“选择一个测试项目”
- javascript - 仅获取 2019 年 1 月 1 日星期二 11:35:00 GMT+0530(印度标准时间)的日期,而不是原型
- javascript - 承诺在“then”函数之外访问值