typescript報錯集錦
- 錯誤:Import sources within a group must be alphabetized.tslint(ordered-imports)
原因:import名稱排序問題,要求按照字母從小到大排序;
解決方案:修改 tslint.json 中 rules 的規則 “ordered-imports” 為 false 即可。
"rules": {
"ordered-imports": false
}
- vscode打開ts項目,cpu爆滿,溫度升高
原因:code helper進程占用過高,系統與軟件問題
解決方案:修改vs code用戶設置
"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中是會發生報錯的:
let a = {};
a.b = 1;
// 終端編譯報錯:TS2339: Property 'b' does not exist on type '{}'.
// 編輯器報錯:[ts] 類型“{}”上不存在屬性“b”。
解決方案:
這是因為TypeScript不允許增加沒有聲明的屬性。
因此,我們有兩個辦法來解決這個報錯:
在對象中增加屬性定義(推薦)。具體方式為:let a = {b: void 0};。這個方法能夠從根本上解決當前問題,也能夠避免對象被隨意賦值的問題。
給a對象增加any屬性(應急)。具體方式為:let a: any = {};。這個方法能夠讓TypeScript類型檢查時忽略這個對象,從而編譯通過不報錯。這個方法適用於大量舊代碼改造的情況。
- 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”的類型不兼容。
解決方案:router4會給我們提供一個RouteComponentProps接口,在文檔中沒說明,自己去代碼中看,將類型加入到代碼中
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));