在react項(xiàng)目中使用typescript

1.安裝typescript,可以全局或者在項(xiàng)目下安裝,這里在當(dāng)前項(xiàng)目下安裝:

yarn add typescript --save

2.安裝常用模塊的類型定義文件@types,如:react、react-dom

yarn add @types/react @types/react-dom --save

需要安裝類型定義文件的模塊,如果沒有安裝,項(xiàng)目編譯時(shí)會(huì)有錯(cuò)誤提示,里面含有 @types/xxx,可以按照提示安裝

3.修改.js文件后綴為 .tsx

tsconfig.json文件里面定義了typescript管理的文件范圍,編譯器默認(rèn)包含當(dāng)前目錄和子目錄下所有的TypeScript文件(.ts, .d.ts 和 .tsx)

"compilerOptions": {
  // 是否編譯js文件,設(shè)置為true時(shí)typescript會(huì)去查找后綴為.js的文件,如果只想編譯.ts、.d.ts 和.tsx文件,則設(shè)置為false
   "allowJs": false,
}
include": [
   "src"
 ]

表示 src 目錄下的.ts、.d.ts 和.tsx文件(如果tsconfig.json中allowJs設(shè)置為true那么還包含.js和.jsx文件)由typescript管理

4.聲明變量的類型

注:這里使用type做示例,interface與type相同作用基本,可自己詳細(xì)了解

①class組件

import {withRouter, RouteComponentProps} from 'react-router-dom';

type PathParamsType = {
  // type whatever you expect in the this.props.match.params.*
}
type PropsType = RouteComponentProps<PathParamsType> & {
  // your props here
  name: string, // 必傳的參數(shù),string類型
  sex: boolean,// 必傳的參數(shù),number類型
  age?: number, // 可選參數(shù),傳的話必須是number類型
  [propName: string]: any // 兼容以上聲明屬性之外的屬性,任意類型any,沒有的話這個(gè)組件不支持傳入name、sex、age以外的參數(shù)
}

class MyComponent extends React.Component<PropsType> {
   render() {
     return (<span>測(cè)試</span>)
   }
}
export default withRouter(MyComponent);

②function組件

import {RouteComponentProps} from 'react-router-dom';

type PathParamsType = {
    // type whatever you expect in the this.props.match.params.*
}
type PropsType = RouteComponentProps<PathParamsType> & {
  name: string, // 必傳的參數(shù),string類型
}
function Auth(props: PropsType) {
    return (
        <div>
            <h2>你的權(quán)限不夠,請(qǐng)使用admin登錄</h2>
       </div>
    );
}

export default Auth;

③.函數(shù)

/**
 * 判斷參數(shù)是哪種類型
 * @param {any} obj
 * @param {string} type
 */
function checkType(obj: object, type?: string) {
  return Object.prototype.toString.call(obj).toLowerCase() === `[object ${type}]`
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容