Skip to content

React 使用 TypeScript

输入 Props, 状态, 事件, and 组件 for 类型-safe React applications.

你将学到

  • 输入组件 Props 使用接口 and 类型
  • 输入 useState, useRef, and 事件处理函数
  • Using React.FC and alternative 输入方法
  • 输入上下文, refs, and generic 组件

概念讲解

Why TypeScript with React?

TypeScript adds static type checking to JavaScript, catching errors at compile time before they reach the browser. In React, this means you get type safety for props (a parent cannot pass the wrong type to a child), autocomplete for component APIs, and self-documenting code. When you rename a prop, the compiler tells you every place that needs updating. For any project beyond a prototype, TypeScript is the recommended choice and is the default in frameworks like Next.js and Create React App's TypeScript template.

Typing Props

Define an interface or type alias for your component's props and use it as the generic parameter: 函数 UserCard({ name, age }: UserCardProps) {}. For children, use React.ReactNode. For event handlers, use the specific React event types: React.ChangeEvent<HTMLInputElement> for input changes, React.MouseEvent<HTMLButtonElement> for button clicks. These types give you autocomplete for event properties and prevent accessing non-existent properties.

Typing Hooks

useState infers the type from the initial value. For complex types or when the initial value is null, provide a generic: useState<用户 | 空>(空). useRef needs a generic when the ref is used for a DOM element: useRef<HTMLInputElement>(空). useContext infers the type from the context's creation. For useReducer, type the state and action union type to get exhaustive switch checking.

React.FC and Alternatives

React.FC (formerly React.FunctionComponent) is a type for function components, but it is no longer recommended as the default. It implicitly adds children to props (which you may not want) and has subtle differences with default props. The preferred approach is to type the props directly in the function signature: 函数 MyComponent(Props: MyProps): JSX.元素 {}. This is more explicit and gives you better control.

Utility Types for Props

TypeScript provides utility types that are useful for component props. 部分<T> makes all props optional. 选取<T, 键> selects specific props from a type. Omit<T, 键> removes specific props. ComponentProps<typeof 组件> extracts the props type of an existing component. These let you build prop types from existing ones without duplication, keeping your types DRY and maintainable.

示例代码

              import { useState, useRef, createContext, useContext } from "react";

// Type the props with an interface.
interface UserCardProps {
  name: string;
  age: number;
  role?: "admin" | "user"; // Optional union type.
  onSelect?: (id: number) => void;
}

function UserCard({ name, age, role = "user", onSelect }: UserCardProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [isEditing, setIsEditing] = useState<boolean>(false);

  // Type the event handler with the specific React event type.
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.value);
  };

  return (
    <div>
      <h3>{name} ({age}) — {role}</h3>
      <input ref={inputRef} onChange={handleChange} />
      {onSelect && <button onClick={() => onSelect(1)}>Select</button>}
    </div>
  );
}

// Typed context.
interface ThemeContextType {
  theme: "light" | "dark";
  toggle: () => void;
}
const ThemeContext = createContext<ThemeContextType | null>(null);

function useTheme(): ThemeContextType {
  const ctx = useContext(ThemeContext);
  if (!ctx) throw new Error("useTheme must be used within ThemeProvider");
  return ctx;
}
            

Props 是输入使用接口, 包含可选 and union 类型. 事件处理函数 use 特定 React 事件类型. useRef and createContext use generics for 类型 safety.

动手试一试

  • JSON Formatter

    TypeScript 接口经常 mirror JSON shapes — 格式到 compare.

  • Code Diff

    Compare 类型定义当 refactoring 组件 APIs.

常见错误

错误写法

Using React.FC for 所有组件通过默认

正确做法

React.FC implicitly 添加 children 到 Props and 有 quirks 使用 generics and 默认 Props. Prefer 输入 Props directly in 函数 signature: 函数 MyComponent(Props: MyProps) {}. 它是 更多 explicit and flexible.

错误写法

Using '任何' for 事件类型相反的 特定 React 事件类型

正确做法

Use React.ChangeEvent<HTMLInputElement>, React.MouseEvent<HTMLButtonElement>, etc. 这些 give 你 autocomplete and 类型检查 for 事件属性. '任何' defeats purpose 的 TypeScript.

练习 React 使用 TypeScript

1 个练习

练习 React 使用 TypeScript

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误