我在Typescript中有一个Vuejs项目。项目编译和运行完美无误。但是TS的短讯是错误的。
我在各个组件文件中使用组件装饰器,如下所示:
//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",
]
}
我想你已经很接近了,我能找到的唯一问题是tsconfig.json
中的include
你的tsconfig.json
是否放置在你的项目之外,所以你需要assets/js/video-app/src
路径?
通常,如果tsconfig.json
在项目中,则include
应如下所示。如果包含路径不正确,则自定义类型定义将不起作用。
"include": [
"src/**/*.ts"
]
你能检查一下static_url.d.ts
是否也在src
目录中吗。
我制作了一个git repo来模拟您的情况,您可以与您的设置进行交叉检查。
Git Repo
如果在这种情况下类型准确性不重要,您可以执行:
(this as any).static_url
如果类型准确性是一个问题,那么我的2美分是,你不应该修改Vue原型。。。在我看来,这不是最好的做法(只是我的PTSD从调试项目中开始,默认对象原型充斥着非标准属性,把一切都搞砸了,并产生了各种讨厌的bug(。如果您有某种状态管理框架,如Vuex,我建议将这些数据存储在Vuex状态中。
或者破解一切,你不需要将你的数据从窗口对象复制到Vue.prototype
(window as any).static_url