关于TypeScript的踩坑记录

 更新时间:2022年09月23日 10:20:15   作者:lihefei_coder  
这篇文章主要介绍了关于TypeScript的踩坑记录,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

用字符串做下标报错

代码示例

const person = {
    name: '张三',
    age: 10
};
function getValue(arg: string) {
    return person[arg];
}

错误信息

Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘{ name: string; age: number; }’.
No index signature with a parameter of type ‘string’ was found on type ‘{ name: string; age: number; }’.ts(7053)

解决方法1

在tsconfig.json中配置suppressImplicitAnyIndexErrors: true

{
    "compilerOptions": {
        "suppressImplicitAnyIndexErrors": true,
        ...
    },
    ...
}

解决方法2

给person定义接口

const person = {
    name: '张三',
    age: 10
};
function getValue(arg: string) {
	interface IPerson {
		[key: string]: any
	}
    return (<IPerson>person)[arg];
}

函数内使用this报错

代码示例

function test() {
    this.title = 'hello'; 
}

错误信息

‘this’ implicitly has type ‘any’ because it does not have a type annotation.ts(2683)

解决方法

在tsconfig.json中配置noImplicitThis: true

{
    "compilerOptions": {
        "noImplicitThis": true,
        ...
    },
    ...
}

找不到模块XXX

代码示例

import CryptoJS from 'crypto-js';

错误信息

Cannot find module ‘crypto-js’.ts(2307)

解决方法

安装对应的声明文件

cnpm install --save-dev @types/crypto-js

模块声明文件搜索: https://microsoft.github.io/TypeSearch/

如果安装不了或搜不到声明文件,请看下面这种方法

引入模块提示找不到声明文件(接上一个问题)

示例代码

import CryptoJS from 'crypto-js'; 

错误信息

解决方法

在src目录下修改shims-vue.d.ts声明文件,在末尾增加一行 declare module 'xxx模块名';

shims-vue.d.ts文件内容如下:

declare module '*.vue' {
    import Vue from 'vue';
    export default Vue;
}
declare module 'crypto-js';

JSON直接解析localStorage值报错

代码示例

JSON.parse(window.localStorage.getItem('token'));

错误信息

Argument of type ‘string | null’ is not assignable to parameter of type ‘string’.
Type ‘null’ is not assignable to type ‘string’.ts(2345)

解决方法

定义一个指定类型为string的变量接收localStorage值

let token: string | null = window.localStorage.getItem('token');
if (token) {
	JSON.parse(token);
}

初始加载的组件未命名,浏览器打开页面后控制台报错

代码示例

//index.vue
@Component
export default class extends Vue {}
//router.ts
import Index from '@/views/index.vue';
const routes: Array<RouteConfig> = [
    {
        path: '/',
        name: 'index',
        component: Index,
    }
];

错误信息

Invalid component name: “_class2”. Component names should conform to valid custom element name in html5 specification.

解决方法

给初始加载的组件命名

//index.vue
@Component({
	name: 'Index'
})
export default class extends Vue {}

初始值未定义类型,后面赋值报错

代码示例

export default class extends Vue {
    private search = {
        name: '',
        types: [];
    };
	
    private typesChange(value: string[]) {
        this.search.types = value; //这里报错
    }
}

错误信息

Type ‘string[]’ is not assignable to type ‘never[]’.
Type ‘string’ is not assignable to type ‘never’.

解决方法

给初始赋值类型断言

export default class extends Vue {
    private search = {
        name: '',
        types: [] as string[]; //这里加断言
    };
	
    private typesChange(value: string[]) {
        this.search.types = value; 
    }
}

在Vue原型上添加属性使用时报错

示例代码

import Vue from 'vue';
import http from './http';
Vue.prototype.$http = http;
this.$http.post('/test', {}).then(
   (resolve: any) => {
       console.log(resolve);
   },
   (reject: any) => {
       console.log(reject);
   }
);

错误信息

解决方法

在src目录下新建vue.d.ts声明文件

vue.d.ts文件内容如下:

import Vue from 'vue';
declare module 'vue/types/vue' {
    interface Vue {
        $http: any;
    }
}

element-ui使用$message报错

解决方法

在src目录下新建vue.d.ts声明文件

vue.d.ts文件内容如下:

import Vue from 'vue';
import { ElMessage } from 'element-ui/types/message';
declare module 'vue/types/vue' {
    interface Vue {
        $message: ElMessage;
    }
}

vue-cli里使用process对象报错类型找不到

解决方法

修改项目根目录下的tsconfig.json文件中的compilerOptions.types值,新增node

compilerOptions.types配置内容如下:

"compilerOptions": {
    "types": ["webpack-env", "node"],
}

vue-cli里tsconfig.json文件报错

错误信息

JSON schema for the typescript compiler's configuration file.
cannot find type definition file for 'webpack-env'.

解决方法

没找到好的解决方法,偶然间尝试了下面的方法居然就不报错了,这种方法不一定适用所有人的项目

修改项目根目录下的tsconfig.json文件中的compilerOptions.types值,先新增"nodejs",再删除"nodejs"

先新增:

"compilerOptions": {
    "types": ["webpack-env", "nodejs"],
}

再删除:

"compilerOptions": {
    "types": ["webpack-env"],
}

边踩坑,边更新。。。

————————————分割线————————————

tsconfig.json配置解释

{
    "compilerOptions": {
        "noEmitOnError": true // 编译的源文件中存在错误的时候不再输出编译结果文件
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Vue中如何实现轮播图的示例代码

    Vue中如何实现轮播图的示例代码

    本篇文章主要介绍了Vue中如何实现轮播图的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-07-07
  • VUE 解决mode为history页面为空白的问题

    VUE 解决mode为history页面为空白的问题

    今天小编就为大家分享一篇VUE 解决mode为history页面为空白的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-11-11
  • 使用Element时默认勾选表格toggleRowSelection方式

    使用Element时默认勾选表格toggleRowSelection方式

    这篇文章主要介绍了使用Element时默认勾选表格toggleRowSelection方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-10-10
  • vue实现At人文本输入框示例详解

    vue实现At人文本输入框示例详解

    这篇文章主要为大家介绍了vue实现At人文本输入框示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • vue中的config目录下index.js解读

    vue中的config目录下index.js解读

    这篇文章主要介绍了vue中的config目录下index.js解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • 基于Vue+Openlayer实现动态加载geojson的方法

    基于Vue+Openlayer实现动态加载geojson的方法

    本文通过实例代码给大家介绍基于Vue+Openlayer实现动态加载geojson的方法,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2021-09-09
  • 解决vue2.x中数据渲染以及vuex缓存的问题

    解决vue2.x中数据渲染以及vuex缓存的问题

    本篇文章主要介绍了vue2.x中请求之前数据显示以及vuex缓存的问题,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-07-07
  • vue3中element-plus icon图标的正确使用姿势

    vue3中element-plus icon图标的正确使用姿势

    element-plus官方提示,Icon图标正在向SVG Icon迁移,之前使用的Font Icon即将被弃用,下面这篇文章主要给大家介绍了关于vue3中element-plus icon图标的正确使用姿势,需要的朋友可以参考下
    2022-03-03
  • Vue中的百度地图定位BMap.GeolocationControl的用法

    Vue中的百度地图定位BMap.GeolocationControl的用法

    BMap.GeolocationControl 是百度地图API中的一个类,用于添加地理定位控件到地图上,以便用户可以通过该控件获取自己的当前位置,本文给大家介绍Vue中的百度地图定位BMap.GeolocationControl的用法,感兴趣的朋友跟随小编一起看看吧
    2023-10-10
  • vue-router的hooks用法详解

    vue-router的hooks用法详解

    这篇文章主要介绍了vue-router的hooks用法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-06-06

最新评论