錯誤信息列表
對全局變量報錯
// 錯誤碼 TS2345
process.env.PUBLIC_URL
解決:
(<any>process).env.PUBLIC_URL
或者 .d.ts
中去聲明
declare var process: any
Cannot find module './logo.svg'
.d.ts
中去聲明
declare module '*.svg'
declare module '*.png'
declare module '*.jpg'
declare module '*.jpeg'
declare module '*.gif'
declare module '*.bmp'
declare module '*.tiff'
導入類似 jQuery、vant/lib 之類無 ts 聲明的組件時錯誤提示
import { Toast } from "vant/lib";
解決:
編寫 .d.ts
文件去聲明
declare module 'vant/lib' {
export * from 'vant'
}
// 類似的還有在 vue 中引入 .vue 文件需要 declare 去聲明
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning
解決:
"experimentalDecorators": true,
typescript 遇到 react 的 withRouter 報錯
Argument of type 'typeof HOC' is not assignable to parameter of type 'ComponentClass<RouteComponentProps<any, StaticContext, any>, any> | FunctionComponent<RouteComponentProps<any, StaticContext, any>> | (FunctionComponent<...> & ComponentClass<...>) | (ComponentClass<...> & FunctionComponent<...>)'.
解決:
withRouter(HOC as any)
webpack 的別名 alias 引起問題
解決:
tsconfig.json
中配置
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
]
}
]
同時 .d.ts
中聲明
declare module '@/*'
typescript 遇到 Property 'xxx' does not exist on type 'xxx'
navigator.camera.getPicture // 這裏 camera 報錯
解決:
(navigator as any).camera.getPicture()
(this.props as any).form
或者提前聲明
type Props = {
setUser: any,
form: any
}
class Login extends React.Component<Props> {
handleSubmit = (e: any) => {
e.preventDefault();
this.props.form.validateFields((err: any, values: any) => {
if (!err) {
}
});
};
render() {
const { getFieldDecorator } = this.props.form;
}
}
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Toast'
對 obj[key]
這樣缺少索引簽名的索引對象報錯
解決:
// tsconfig.json 中配置下面以組織此報錯
"suppressImplicitAnyIndexErrors": true,
Cannot find name "xxx"
是因爲變量未定義就使用,如果非要使用,可以提前聲明
declare function xxx(s:any): any
declare function xxx(s:string): string
Subsequent property declarations must have the same type. Property '$notify' must be of type 'Notify', but here has type 'ElNotification'
框架內 .d.ts
聲明衝突
解決:
"skipLibCheck": true,
Type error: Cannot compile namespaces when the '--isolatedModules' flag is provided
解決:
"isolatedModules": false
忽略錯誤
單行忽略
// @ts-ignore
忽略全文
// @ts-nocheck
取消忽略全文
// @ts-check
例如:cordova 插件使用忽略報錯
// @ts-ignore
cordova.InAppBrowser.open(encodeURI(url), "_system", "location=no,toolbar=yes,toolbarposition=top,closebuttoncaption=關閉");