react+typescript报错集锦<持续更新>

typescript报错集锦

  • 错误:Import sources within a group must be alphabetized.tslint(ordered-imports)

缘由:import名称排序问题,要求按照字母从小到大排序;node

解决方案:修改 tslint.json 中 rules 的规则 “ordered-imports” 为 false 便可。react

"rules": {
  "ordered-imports": false
}
  • vscode打开ts项目,cpu爆满,温度升高

缘由:code helper进程占用太高,系统与软件问题
解决方案:修改vs code用户设置git

"files.exclude": {
        "**/.git": true,
        "**/.svn": true,
        "**/.hg": true,
        "**/CVS": true,
        "**/.DS_Store": true,
        "**/tmp": true,
        "**/node_modules": true,
        "**/bower_components": true,
        "**/dist": true
    },
    "files.watcherExclude": {
        "**/.git/objects/**": true,
        "**/.git/subtree-cache/**": true,
        "**/node_modules/**": true,
        "**/tmp/**": true,
        "**/bower_components/**": true,
        "**/dist/**": true
    }
  • 对象属性赋值报错

缘由:在JavaScript中,咱们常常会声明一个空对象,而后再给这个属性进行赋值。可是这个操做放在TypeScript中是会发生报错的:typescript

let a = {};

a.b = 1;

// 终端编译报错:TS2339: Property 'b' does not exist on type '{}'.
// 编辑器报错:[ts] 类型“{}”上不存在属性“b”。

解决方案:json

这是由于TypeScript不容许增长没有声明的属性。
所以,咱们有两个办法来解决这个报错:
在对象中增长属性定义(推荐)。具体方式为:let a = {b: void 0};。这个方法可以从根本上解决当前问题,也可以避免对象被随意赋值的问题。
给a对象增长any属性(应急)。具体方式为:let a: any = {};。这个方法可以让TypeScript类型检查时忽略这个对象,从而编译经过不报错。这个方法适用于大量旧代码改造的状况。redux

  • react-redux react-router4在typescript类型检查下报类型错误
    缘由:在react项目中,页面须要获取路由信息,且在用了react-redux的状况下,须要将路由与redux作关联
    正常写法:
import { connect } from 'react-redux';
import { actionCreators } from './store'
import { withRouter } from 'react-router-dom';

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));

react使用了typescript状况下:会报错:
错误提示:类型“ConnectedComponentClass<typeof Login, Pick<LoginProps, "handleNameChange" | "handlePassWordChange" | "handleSubmit">>”的参数不能赋给类型“ComponentType<RouteComponentProps<any, StaticContext, any>>”的参数。 不能将类型“ConnectedComponentClass<typeof Login, Pick<LoginProps, "handleNameChange" | "handlePassWordChange" | "handleSubmit">>”分配给类型“ComponentClass<RouteComponentProps<any, StaticContext, any>, any>”。 属性“propTypes”的类型不兼容。
react-router

解决方案:router4会给咱们提供一个RouteComponentProps接口,在文档中没说明,本身去代码中看,将类型加入到代码中dom

import { connect } from 'react-redux';
import { withRouter, RouteComponentProps } from 'react-router-dom';
interface Props {
}
class Login extends Component<RouteComponentProps & Props>{}
withRouter(connect(mapStateToProps, mapDispatchToProps)(Login));
相关文章
相关标签/搜索