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文件报错

代码示例

import zh from './zh.json'

错误信息

Cannot find module ‘./zh.json’. Consider using ‘–resolveJsonModule’ to import module with ‘.json’ extension.ts(2732)

解决方法
在tsconfig.json的compilerOptions下添加这些设置:

"resolveJsonModule": true,
"esModuleInterop": true,

🐞 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"],
}

🐞 new实例化报错

代码示例

import mitt from 'mitt';
app.config.globalProperties.$bus = new mitt();

错误信息

‘new’ expression, whose target lacks a construct signature, implicitly has an ‘any’ type.ts(7009)

解决方法
包上(xxx as any)

app.config.globalProperties.$bus = new (mitt() as any) ;

边踩坑,边更新。。。

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

tsconfig.json配置解释

{
    "compilerOptions": {
        "noEmitOnError": true // 编译的源文件中存在错误的时候不再输出编译结果文件
    }
}
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值