# React TypeScript
类型安全的 React = 编译时保证 = 可靠的重构。
- 构建类型化的 React 组件
- 实现泛型组件
- 类型化事件处理程序、表单、Refs
- 使用 React 19 特性 (Actions, 服务端组件, use())
- 路由集成 (TanStack Router, React Router)
- 自定义钩子的正确类型化
不适用于:非 React 的 TypeScript 项目,原生 JS React
React 19 的破坏性变更需要迁移。关键模式:
**ref 作为 prop** - forwardRef 已弃用:
typescript
// React 19 - ref 作为普通 prop
type ButtonProps = {
ref?: React.Ref;
} & React.ComponentPropsWithoutRef;
function Button({ ref, children, ...props }: ButtonProps) {
return
;
}
**useActionState** - 替代 useFormState:
typescript
import { useActionState } from 'react';
type FormState = { errors?: string[]; success?: boolean };
function Form() {
const [state, formAction, isPending] = useActionState(submitAction, {});
return ...;
}
**use()** - 解包 Promise/Context:
typescript
function UserProfile({ userPromise }: { userPromise: Promise }) {
const user = use(userPromise); // 挂起直到解析完成
return
{user.name}
;
}
查看 [react-19-patterns.md](references/react-19-patterns.md) 获取关于 useOptimistic, useTransition 和迁移清单的信息。
**Props** - 扩展原生元素:
typescript
type ButtonProps = {
variant: 'primary' | 'secondary';
} & React.ComponentPropsWithoutRef;
function Button({ variant, children, ...props }: ButtonProps) {
return
;
}
**Children 类型化**:
typescript
type Props = {
children: React.ReactNode; // 任何可渲染内容
icon: React.ReactElement; // 单个元素
render: (data: T) => React.ReactNode; // 渲染 prop
};
**可辨识联合 (Discriminated unions)** 用于变体 Props:
typescript
type ButtonProps =
| { variant: 'link'; href: string }
| { variant: 'button'; onClick: () => void };
function Button(props: ButtonProps) {
if (props.variant === 'link') {
return
Link;
}
return
;
}
使用特定的事件类型以实现精确的目标类型化:
typescript