React with TypeScript(Total TypeScript)
Total TypeScript 的免费 React with TypeScript 课程框架笔记,按 Introduction、Components、Hooks 三部分记录 21 个练习的学习内容。
[!info] related notes
- 相关主题: react-typescript-component-and-hook-types
- 相关 MOC:
- 相关 howto:
React with TypeScript(Total TypeScript)
课程概览
- 课程:React with TypeScript
- 平台:Total TypeScript
- 作者:Matt Pocock
- 形式:免费、练习驱动课程;每个练习通常包含 Problem / Exercise / Solution
- 课程结构:3 个 Section,共 21 个学习项
- 记录方式:每学完一节,在对应标题下补充“讲了什么”。如果某个知识点值得长期复用,再单独沉淀成 concept / synthesis 笔记并从这里链接过去。
01 Introduction
01 React in TypeScript
讲了什么: 第一课讲了 React 和 TypeScript 是怎么配合的。首先,你的类型文件需要变成 TSX,然后需要在 package 中引入类型的包,React 的类型包。并且要在 tsconfig 中添加 jsx 的配置,并且默认是 preserve。
// Explain how React works with TypeScript // tsconfig options: jsx: “preserve” // @types/react
02 TypeScript in React Frameworks
讲了什么:
- 基础的给 props 添加类型
- 给整个函数组件添加类型 React.FC<>
- add type to props.children : React.ReactNode, one type that represents everything that can be rendered
- add type to onclick : React.MouseEventHandler<> ; 还有一个就是精度问题, 可以不传入 T,使用默认的 Element, 但是此时就只能访问 Element 公有的属性, 使用更精确的 HTMLButtonElement 就可以使用 disabled
- use
ComponentProps<"button">to get all the props from a component - use Omit<T, K extends keyof any> to remove(overriding) component props
- use
ComponentProps<typeof ComponentName>to extract props from custom compoenents
03 Navigating JSX Types
讲了什么:
02 Components
04 Typing Components
讲了什么:
05 Typing Components as Functions
讲了什么:
06 Typing Children
讲了什么:
07 Typing onClick Handlers
讲了什么:
08 Using HTML Props
讲了什么:
09 HTML Props with One Changed
讲了什么:
10 Extracting Props from Custom Components
讲了什么:
03 Hooks
11 useState
讲了什么: useState<>
12 useState with undefined
讲了什么: useState 通过 TypeScript 函数重载,根据是否提供初始值决定 State 是否自动包含 undefined;如果希望使用 null 表示空状态,则需要显式声明 T | null。
13 useState Excess Properties
讲了什么: TS Structural Typing 的设计让返回值多处一些奇怪属性时不会报错,在 react 的替换思想下,容易出现一些错误,需要强制约束返回类型
onClick={() => {
setState((currentState): TagState => ({
…currentState,
// @ts-expect-error
tagselected: tag.id,
}));
}}
14 useEffect
讲了什么:
import { useEffect } from "react";
export const useTimeout = (timerMs: number) => {
useEffect(
() =>
setTimeout(() => {
console.log("Done!");
}, timerMs),
[timerMs],
);
};
这里会报错是因为 () => xxx 等于默认返回了 timeout,导致不符合 useEffect 的类型规范 关键就是晕倒奇怪的错误时,根据类型诊断来查明原因
15 useCallback
讲了什么:
function useCallback<T extends Function>(callback: T, deps: DependencyList): T;
react typescript 有很强的推测能力
16 useMemo
讲了什么:
不要猜
17 useRef Basics
讲了什么:
useRef<string>()
18 Element Refs
讲了什么: ref and HTMLElement
19 useRef with Elements
讲了什么:
DOM Ref = useRef<对应的 HTMLElement 类型>(null);不知道 HTMLElement 类型就 hover 查,不要用 any 糊过去。
20 Why Is My Ref Readonly?
讲了什么:
旧版 React typings 曾经尝试通过 useRef<T>(null) 识别“React 管理的 ref”,因此让这个 overload 返回 readonly RefObject<T>;这只是 TypeScript overload 造成的类型行为,不是 null 本身导致的。
21 useReducer
讲了什么:
联合类型是在 structural typing 的基础上,列举多个“允许的对象结构”,再通过 type 字段把这些结构区分开。