vue-typescript遇到的问题

3,630 阅读1分钟

问题一:
报错:
Type string trivially inferred from a string literal, remove type annotation (no-inferrable-types)

About.vue代码:

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <p>{{ word }}</p>
  </div>
</template>

<script lang="ts">
  import Vue from 'vue';
  import Component from 'vue-class-component';
  @Component
  export default class About extends Vue {
    word: string = "你好!";//导致了tslint报错
  }
</script>

究其原因可能是tslint觉得自己根据右边的"你好"判断出word的类型是string,所以,认为再写string是多此一举。

解决方法:tslint.json添加"ignore-properties"。不推断类的属性(字段) 代码如下:

{
  "rulesDirectory": ["./src/views/About.vue"],
  "rules": {
    "no-inferrable-types": [true, "ignore-params", "ignore-properties"]
  }
}

问题二
vue+typescript项目中import.vue文件报错
究其原因是因为typescript不能导入.vue文件
解决方法:新建一个xxx-vue.dt.ts文件,放在vue-cli根目录或者src目录下,
写法如下:

declare module '*.vue'{
    import Vue from 'vue'
    export default Vue
}

问题三
vue+typescript项目使用@引入无法找到模块
这是因为typescript不能自动地处理webpack的别名
解决办法:为了让ts处理别名,需要在tsconfig.json中配置paths 写法如下:

{
 "compilerOptions":{
     "paths":{
         "@/*":["src/*"]
     }
 }
}

参考链接:
typescript -入门 www.jianshu.com/p/8ba2cdbfa…

配置TSLint:palantir.github.io/tslint/usag…