前言
一直以來,ssh 身邊都有很多小伙伴對 TS 如何在 React 中運用有很多困惑,他們開始慢慢討厭 TS,覺得各種莫名其妙的問題降低了開發的效率。
其實如果運用熟練的話,TS 只是在第一次開發的時候稍微多花一些時間去編寫類型,后續維護、重構的時候就會發揮它神奇的作用了,還是非常推薦長期維護的項目使用它的。
其實我一直知道英文版有個不錯的備忘錄,本來想直接推薦給小伙伴,奈何很多人對英文比較頭痛,而它中文翻譯的版本點進去竟然是這個景象:
既然如此,就自己動手。結合英文原版里的一些示例進行一些擴展,總結成這篇備忘錄。
前置基礎
閱讀本文的前提條件是:
- 熟悉 React 的使用。
- 熟悉 TypeScript 中的類型知識。
- 本文會側重使用 React Hook 作為示例,當然大部分類型知識都是通用的。
也就是說,這篇文章側重點在于 「React 和 TypeScript 的結合」,而不是基礎知識,基礎知識閱讀文檔即可學習。
工具
- TypeScript Playground with React:可以在線調試 React + TypeScript,只能調試類型,并不能運行代碼
- Stackblitz:云開發工具,可以直接運行 React 代碼并且預覽
- Create React App TypeScript: 本地用腳手架生成 React + TS 的項目
選擇你覺得比較中意的調試工具即可。
組件 Props
先看幾種定義 Props 經常用到的類型:
基礎類型
- type BasicProps = {
- message: string;
- count: number;
- disabled: boolean;
- /** 數組類型 */
- names: string[];
- /** 用「聯合類型」限制為下面兩種「字符串字面量」類型 */
- status: "waiting" | "success";
- };
對象類型
- type ObjectOrArrayProps = {
- /** 如果你不需要用到具體的屬性 可以這樣模糊規定是個對象 ? 不推薦 */
- obj: object;
- obj2: {}; // 同上
- /** 擁有具體屬性的對象類型 ? 推薦 */
- obj3: {
- id: string;
- title: string;
- };
- /** 對象數組 常用 */
- objArr: {
- id: string;
- title: string;
- }[];
- /** key 可以為任意 string,值限制為 MyTypeHere 類型 */
- dict1: {
- [key: string]: MyTypeHere;
- };
- dict2: Record<string, MyTypeHere>; // 基本上和 dict1 相同,用了 TS 內置的 Record 類型。
- }
函數類型
- type FunctionProps = {
- /** 任意的函數類型 ? 不推薦 不能規定參數以及返回值類型 */
- onSomething: Function;
- /** 沒有參數的函數 不需要返回值 常用 */
- onClick: () => void;
- /** 帶函數的參數 非常常用 */
- onChange: (id: number) => void;
- /** 另一種函數語法 參數是 React 的按鈕事件 非常常用 */
- onClick(event: React.MouseEvent<HTMLButtonElement>): void;
- /** 可選參數類型 非常常用 */
- optional?: OptionalType;
- }
React 相關類型
- export declare interface AppProps {
- children1: JSX.Element; // ? 不推薦 沒有考慮數組
- children2: JSX.Element | JSX.Element[]; // ? 不推薦 沒有考慮字符串 children
- children4: React.ReactChild[]; // 稍微好點 但是沒考慮 null
- children: React.ReactNode; // ? 包含所有 children 情況
- functionChildren: (name: string) => React.ReactNode; // ? 返回 React 節點的函數
- style?: React.CSSProperties; // ? 推薦 在內聯 style 時使用
- // ? 推薦原生 button 標簽自帶的所有 props 類型
- // 也可以在泛型的位置傳入組件 提取組件的 Props 類型
- props: React.ComponentProps<"button">;
- // ? 推薦 利用上一步的做法 再進一步的提取出原生的 onClick 函數類型
- // 此時函數的第一個參數會自動推斷為 React 的點擊事件類型
- onClickButton:React.ComponentProps<"button">["onClick"]
- }
函數式組件
最簡單的:
- interface AppProps = { message: string };
- const App = ({ message }: AppProps) => <div>{message}</div>;
包含 children 的:
利用 React.FC 內置類型的話,不光會包含你定義的 AppProps 還會自動加上一個 children 類型,以及其他組件上會出現的類型:
- // 等同于
- AppProps & {
- children: React.ReactNode
- propTypes?: WeakValidationMap<P>;
- contextTypes?: ValidationMap<any>;
- defaultProps?: Partial<P>;
- displayName?: string;
- }
- // 使用
- interface AppProps = { message: string };
- const App: React.FC<AppProps> = ({ message, children }) => {
- return (
- <>
- {children}
- <div>{message}</div>
- </>
- )
- };
Hooks
@types/react 包在 16.8 以上的版本開始對 Hooks 的支持。
useState
如果你的默認值已經可以說明類型,那么不用手動聲明類型,交給 TS 自動推斷即可:
- // val: boolean
- const [val, toggle] = React.useState(false);
- toggle(false)
- toggle(true)
如果初始值是 null 或 undefined,那就要通過泛型手動傳入你期望的類型。
- const [user, setUser] = React.useState<IUser | null>(null);
- // later...
- setUser(newUser);
這樣也可以保證在你直接訪問 user 上的屬性時,提示你它有可能是 null。
通過 optional-chaining 語法(TS 3.7 以上支持),可以避免這個錯誤。
- // ? ok
- const name = user?.name
useReducer
需要用 Discriminated Unions 來標注 Action 的類型。
- const initialState = { count: 0 };
- type ACTIONTYPE =
- | { type: "increment"; payload: number }
- | { type: "decrement"; payload: string };
- function reducer(state: typeof initialState, action: ACTIONTYPE) {
- switch (action.type) {
- case "increment":
- return { count: state.count + action.payload };
- case "decrement":
- return { count: state.count - Number(action.payload) };
- default:
- throw new Error();
- }
- }
- function Counter() {
- const [state, dispatch] = React.useReducer(reducer, initialState);
- return (
- <>
- Count: {state.count}
- <button onClick={() => dispatch({ type: "decrement", payload: "5" })}>
- -
- </button>
- <button onClick={() => dispatch({ type: "increment", payload: 5 })}>
- +
- </button>
- </>
- );
- }
「Discriminated Unions」一般是一個聯合類型,其中每一個類型都需要通過類似 type 這種特定的字段來區分,當你傳入特定的 type 時,剩下的類型 payload 就會自動匹配推斷。
這樣:
- 當你寫入的 type 匹配到 decrement 的時候,TS 會自動推斷出相應的 payload 應該是 string 類型。
- 當你寫入的 type 匹配到 increment 的時候,則 payload 應該是 number 類型。
這樣在你 dispatch 的時候,輸入對應的 type,就自動提示你剩余的參數類型啦。
useEffect
這里主要需要注意的是,useEffect 傳入的函數,它的返回值要么是一個方法(清理函數),要么就是undefined,其他情況都會報錯。
比較常見的一個情況是,我們的 useEffect 需要執行一個 async 函數,比如:
- // ?
- // Type 'Promise<void>' provides no match
- // for the signature '(): void | undefined'
- useEffect(async () => {
- const user = await getUser()
- setUser(user)
- }, [])
雖然沒有在 async 函數里顯式的返回值,但是 async 函數默認會返回一個 Promise,這會導致 TS 的報錯。
推薦這樣改寫:
- useEffect(() => {
- const getUser = async () => {
- const user = await getUser()
- setUser(user)
- }
- getUser()
- }, [])
或者用自執行函數?不推薦,可讀性不好。
- useEffect(() => {
- (async () => {
- const user = await getUser()
- setUser(user)
- })()
- }, [])
useRef
這個 Hook 在很多時候是沒有初始值的,這樣可以聲明返回對象中 current 屬性的類型:
- const ref2 = useRef(null);
以一個按鈕場景為例:
- function TextInputWithFocusButton() {
- const inputEl = React.useRef<HTMLInputElement>(null);
- const onButtonClick = () => {
- if (inputEl && inputEl.current) {
- inputEl.current.focus();
- }
- };
- return (
- <>
- <input ref={inputEl} type="text" />
- <button onClick={onButtonClick}>Focus the input</button>
- </>
- );
- }
當 onButtonClick 事件觸發時,可以肯定 inputEl 也是有值的,因為組件是同級別渲染的,但是還是依然要做冗余的非空判斷。
有一種辦法可以繞過去。
- const ref1 = useRef(null!);
null! 這種語法是非空斷言,跟在一個值后面表示你斷定它是有值的,所以在你使用 inputEl.current.focus() 的時候,TS 不會給出報錯。
但是這種語法比較危險,需要盡量減少使用。
在絕大部分情況下,inputEl.current?.focus() 是個更安全的選擇,除非這個值真的不可能為空。(比如在使用之前就賦值了)
useImperativeHandle
推薦使用一個自定義的 innerRef 來代替原生的 ref,否則要用到 forwardRef 會搞的類型很復雜。
- type ListProps = {
- innerRef?: React.Ref<{ scrollToTop(): void }>
- }
- function List(props: ListProps) {
- useImperativeHandle(props.innerRef, () => ({
- scrollToTop() { }
- }))
- return null
- }
結合剛剛 useRef 的知識,使用是這樣的:
- function Use() {
- const listRef = useRef<{ scrollToTop(): void }>(null!)
- useEffect(() => {
- listRef.current.scrollToTop()
- }, [])
- return (
- <List innerRef={listRef} />
- )
- }
很完美,是不是?
自定義 Hook
如果你想仿照 useState 的形式,返回一個數組給用戶使用,一定要記得在適當的時候使用 as const,標記這個返回值是個常量,告訴 TS 數組里的值不會刪除,改變順序等等……
否則,你的每一項都會被推斷成是「所有類型可能性的聯合類型」,這會影響用戶使用。
- export function useLoading() {
- const [isLoading, setState] = React.useState(false);
- const load = (aPromise: Promise<any>) => {
- setState(true);
- return aPromise.finally(() => setState(false));
- };
- // ? 加了 as const 會推斷出 [boolean, typeof load]
- // ? 否則會是 (boolean | typeof load)[]
- return [isLoading, load] as const;[]
- }
對了,如果你在用 React Hook 寫一個庫,別忘了把類型也導出給用戶使用。
React API
forwardRef
函數式組件默認不可以加 ref,它不像類組件那樣有自己的實例。這個 API 一般是函數式組件用來接收父組件傳來的 ref。
所以需要標注好實例類型,也就是父組件通過 ref 可以拿到什么樣類型的值。
- type Props = { };
- export type Ref = HTMLButtonElement;
- export const FancyButton = React.forwardRef<Ref, Props>((props, ref) => (
- <button ref={ref} className="MyClassName">
- {props.children}
- </button>
- ));
由于這個例子里直接把 ref 轉發給 button 了,所以直接把類型標注為 HTMLButtonElement 即可。
父組件這樣調用,就可以拿到正確類型:
- export const App = () => {
- const ref = useRef<HTMLButtonElement>()
- return (
- <FancyButton ref={ref} />
- )
- }
原文地址:https://juejin.cn/post/6910863689260204039