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));
相關文章
相關標籤/搜索