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}]`
}