天天看點

[React Typescript 2022] Type React hooks

Type useMemo:

let rowArray = React.useMemo<null[]>(
        () => Array(board.rows).fill(null),
        [board.rows]
    );      

Type useCallback:

let getColumnArray = React.useCallback(
        (rowIndex: number): Cell[] =>
            cells.slice(
                board.columns * rowIndex,
                board.columns * rowIndex + board.columns
            ),
        [board.columns, cells]
    );      

Type useRef:

let ref = React.useRef<HTMLButtonElement>(null);

<Button ref={ref} ... />      

Type useState:

let [timeElapsed, setTimeElapsed] = React.useState<number>(0);      

Type Custom hook:

function useTimer(gameState): [number, () => void] {
    let [timeElapsed, setTimeElapsed] = React.useState<number>(0);
    React.useEffect(() => {
        if (gameState === "active") {
            let id = window.setInterval(() => {
                setTimeElapsed((t) => (t <= 999 ? ++t : t));
            }, 1000);
            return () => {
                window.clearInterval(id);
            };
        }
    }, [gameState]);
    const reset = React.useCallback(() => {
        setTimeElapsed(0);
    }, []);
    return [timeElapsed, reset];
}      

Type useReducer:

The best way to type a useReducer is typing `reducer` function itself.

let [{ gameState, cells, mines }, send] = React.useReducer(
        reducer,
        initialContext,
        function getInitialContext(ctx) {
            return {
                ...ctx,
                cells: createCells(board),
            };
        }
    );      
interface BoardContext {
    gameState: GameState;
    cells: Cell[];
    mines: number[];
    initialized: boolean;
}
type BoardEvent =
    | { type: "RESET"; board: BoardConfig }
    | { type: "REVEAL_CELL"; board: BoardConfig; index: number }
    | { type: "REVEAL_ADJACENT_CELLS"; board: BoardConfig; index: number }
    | { type: "MARK_CELL"; index: number }
    | { type: "MARK_REMAINING_MINES"; board: BoardConfig };
function reducer(context: BoardContext, event: BoardEvent): BoardContext { ... }