Project Icon

react

React与TypeScript集成的全面指南

该指南系统性地介绍了在React项目中集成TypeScript的方法。从基础设置到高级应用,内容全面涵盖了函数组件、Hooks和类组件等关键概念的TypeScript实现。通过实用的代码示例和排错技巧,为不同水平的开发者提供了切实可行的参考。指南致力于提升开发团队在React项目中运用TypeScript的能力和效率。

React+TypeScript Cheatsheets

Cheatsheets for experienced React developers getting started with TypeScript


react + ts logo

Web docs | Español | Português | Contribute! | Ask!

:wave: This repo is maintained by @swyx, @eps1lon and @filiptammergard. We're so happy you want to try out TypeScript with React! If you see anything wrong or missing, please file an issue! :+1:


All Contributors | Discord | Tweet

All React + TypeScript Cheatsheets

  • The Basic Cheatsheet is focused on helping React devs just start using TS in React apps
    • Focus on opinionated best practices, copy+pastable examples.
    • Explains some basic TS types usage and setup along the way.
    • Answers the most Frequently Asked Questions.
    • Does not cover generic type logic in detail. Instead we prefer to teach simple troubleshooting techniques for newbies.
    • The goal is to get effective with TS without learning too much TS.
  • The Advanced Cheatsheet helps show and explain advanced usage of generic types for people writing reusable type utilities/functions/render prop/higher order components and TS+React libraries.
    • It also has miscellaneous tips and tricks for pro users.
    • Advice for contributing to DefinitelyTyped.
    • The goal is to take full advantage of TypeScript.
  • The Migrating Cheatsheet helps collate advice for incrementally migrating large codebases from JS or Flow, from people who have done it.
    • We do not try to convince people to switch, only to help people who have already decided.
    • ⚠️This is a new cheatsheet, all assistance is welcome.
  • The HOC Cheatsheet) specifically teaches people to write HOCs with examples.
    • Familiarity with Generics is necessary.
    • ⚠️This is the newest cheatsheet, all assistance is welcome.

Basic Cheatsheet

Basic Cheatsheet Table of Contents

Expand Table of Contents

Section 1: Setup

Prerequisites

You can use this cheatsheet for reference at any skill level, but basic understanding of React and TypeScript is assumed. Here is a list of prerequisites:

In the cheatsheet we assume you are using the latest versions of React and TypeScript.

React and TypeScript starter kits

React has documentation for how to start a new React project with some of the most popular frameworks. Here's how to start them with TypeScript:

  • Next.js: npx create-next-app@latest --ts
  • Remix: npx create-remix@latest
  • Gatsby: npm init gatsby --ts
  • Expo: npx create-expo-app -t with-typescript

Try React and TypeScript online

There are some tools that let you run React and TypeScript online, which can be helpful for debugging or making sharable reproductions.

Section 2: Getting Started

Function Components

These can be written as normal functions that take a props argument and return a JSX element.

// Declaring type of props - see "Typing Component Props" for more examples
type AppProps = {
  message: string;
}; /* use `interface` if exporting so that consumers can extend */

// Easiest way to declare a Function Component; return type is inferred.
const App = ({ message }: AppProps) => <div>{message}</div>;

// You can choose to annotate the return type so an error is raised if you accidentally return some other type
const App = ({ message }: AppProps): React.JSX.Element => <div>{message}</div>;

// You can also inline the type declaration; eliminates naming the prop types, but looks repetitive
const App = ({ message }: { message: string }) => <div>{message}</div>;

// Alternatively, you can use `React.FunctionComponent` (or `React.FC`), if you prefer.
// With latest React types and TypeScript 5.1. it's mostly a stylistic choice, otherwise discouraged.
const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
  <div>{message}</div>
);
// or
const App: React.FC<AppProps> = ({ message }) => <div>{message}</div>;

Tip: You might use Paul Shen's VS Code Extension to automate the type destructure declaration (incl a keyboard shortcut).

Why is React.FC not needed? What about React.FunctionComponent/React.VoidFunctionComponent?

You may see this in many React+TypeScript codebases:

const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
  <div>{message}</div>
);

However, the general consensus today is that React.FunctionComponent (or the shorthand React.FC) is not needed. If you're still using React 17 or TypeScript lower than 5.1, it is even discouraged. This is a nuanced opinion of course, but if you agree and want to remove React.FC from your codebase, you can use this jscodeshift codemod.

Some differences from the "normal function" version:

  • React.FunctionComponent is explicit about the return type, while the normal function version is implicit (or else needs additional annotation).

  • It provides typechecking and autocomplete for static properties like displayName, propTypes, and defaultProps.

    • Note that there are some known issues using defaultProps with React.FunctionComponent. See this issue for details. We maintain a separate defaultProps section you can also look up.
  • Before the React 18 type updates, React.FunctionComponent provided an implicit definition of children (see below), which was heavily debated and is one of the reasons React.FC was removed from the Create React App TypeScript template.

// before React 18 types
const Title: React.FunctionComponent<{ title: string }> = ({
  children,
  title,
}) => <div title={title}>{children}</div>;
(Deprecated)Using React.VoidFunctionComponent or React.VFC instead

In @types/react 16.9.48, the React.VoidFunctionComponent or React.VFC type was added for typing children explicitly. However, please be aware that React.VFC and React.VoidFunctionComponent were deprecated in React 18 (https://github.com/DefinitelyTyped/DefinitelyTyped/pull/59882), so this interim solution is no longer necessary or recommended in React 18+.

Please use regular function components or React.FC instead.

type Props = { foo: string };

// OK now, in future, error
const FunctionComponent: React.FunctionComponent<Props> = ({
  foo,
  children,
}: Props) => {
  return (
    <div>
      {foo} {children}
    </div>
  ); // OK
};

// Error now, in future, deprecated
const VoidFunctionComponent: React.VoidFunctionComponent<Props> = ({
  foo,
  children,
}) => {
 
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号