用TS写React

1. TS重构项目三种方案

  1. 共存策略: TS和JS共存
  2. 宽松策略: 将现有JS改成TS, 代码检测规则按照宽松的规则执行
  3. 严格策略: 开启最严格的检测规则, 一个一个排除报错

2. TS写函数组件

2.1 函数声明式

// React.ReactNode: 表示返回的内容
function Heading(): React.ReactNode {
  return <h1>My Website Heading</h1>
}

2.2 函数表达式

// React.FC: 因为函数表达式返回一个函数
const OtherHeading: React.FC = () => <h1>My Website Heading</h1>

3. TS 写 useState

const [count, setCount] = useState<number>(0);// 不推荐, 类型注解: number类型
const [count, setCount] = useState(0);// ok, 推荐用类型推导

const [state, setState] = useState<number | null>(null);// 类型注解: 联合类型

type ArticleInfo = {
  title: string;
  content: string;
};
const [articles, setArticles] = useState<ArticleInfo[]>([]);// 类型注解: 数组

4. ES6参数默认值代替React的defaultProps

  • 原因: React.FC不能完美支持defaultProps
import React from 'react'

type Props = {
  color?: string;
  children: React.ReactNode;
  onClick: ()  => void;
}

// color设置了默认值, 代替defaultProps
const Button: React.FC<Props> = ({ children, color = 'tomato', onClick }) => {
   return <button style={{ backgroundColor: color }} onClick={onClick}>{children}</button>
}

5. TS对Redux所有state进行类型约束

// 类型约束: store/index.ts

// 将RootState暴露出去: store中所有state状态进行类型约束
export type RootState = ReturnType<typeof rootReducer>;
// 使用

import { RootState } from '../../store/index'

// 使用RootState约束所有state
const { userReducer, tokenReducer } = useSelector((state: RootState) => state)