本节会列举使用 vscode 进行 ts 开发时,出现的异常问题该如何解决。
错误提示:Parameter 'xxx' implicitly has an 'any' type.ts(7006)
- 解决方案
- 修改
tsconfig.json配置文件,将noImplicitAny修改为 false.
{
"noImplicitAny": false
}- 全局安装
tslint扩展包
$ npm install -g tslint再安装 vscode 插件 TSLint(deprecated)
错误提示:'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
const fn = (a) => {
return function () {
return a.apply(this, arguments)
}
}- 解决方案
- 添加
this: any
const fn = (a) => {
return function (this: any) {
return a.apply(this, arguments)
}
}- 修改
tsconfig.json配置文件,将noImplicitThis修改为 false.
{
"noImplicitThis": false
}- 解决方案
- 注销掉
allowJs或设置为 false,不允许编译 JS 文件(js、jsx)
{
"compilerOptions": {
...
// "allowJs": true,
...
}
}若想允许编译 JS 文件,参考第二种解决办法
- tsconfig 设置
allowJs、noEmit
{
"compilerOptions": {
...
"allowJs": true,
"noEmit": true,
...
}
}noEmit 设置为 true 可能会导致 webpack 进行编译打包时报错,可以采用第三种的解决办法.
- tsconfig 设置
include、exclude
{
"compilerOptions": {
...
"allowJs": true,
// "noEmit": true,
...
},
"include": ["src/**/*.*"],
"exclude": ["node_modules", "build", "dist"]
}这里主要是 include 起作用,本来设置其中一个就可以,但 exclude 并没有作用,可能是个bug.
错误提示:Cannot use JSX unless the '--jsx' flag is provided.
- 解决方案
修改 tsconfig.json
{
"jsx": "react"
}- 解决方案
src 目录下创建 vue-shim.d.ts 文件
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}- 解决方案
-
取消
ts后缀 -
在上一行添加
// @ts-ignore过滤
- 解决方案
修改 tsconfig
// tsconfig.js
{
"compilerOptions": {
...
"types": [
"node"
]
...
}
}安装包
$ npm install @types/node --save-devProperty 'replaceAll' does not exist on type 'string'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2021' or later.ts(2550)
例如:
let date="1399/06/08"
console.log(date.replaceAll('/', '_'))- 解决方案
replace 代替 replaceAll
"1399/06/08".replace(/\//g, "_") // "1399_06_08"或者更改 tsconfig.json
{
...,
"compilerOptions": {
...,
"lib": [
...,
"ES2021.String"
]
}
}- 解决方案
(window as any).xxxdeclare global {
interface Window {
xxx: any
}
}
window.xxx = window.xxx || {}interface MyWindow extends Window {
xxx(): void
}
declare var window: MyWindow