如何使用 Typescript 创建 React 应用程序

介绍

Create React App为您提供了一套必要的包和配置,以便开始构建 React 应用程序。版本 2.0 引入了官方的 TypeScript支持。这使 JavaScript 用户能够在 React 前端框架中使用 TypeScript 公约来编写。

在本文中,您将使用 Create React App 设置一个 React 应用程序与 TypeScript。

前提条件

要跟随这篇文章,你将需要:

本教程已通过 Node v15.13.0、npm v7.8.0、react-scripts v4.0.3、react v17.0.2 和typescript v4.2.3 进行验证。

启动 TypeScript 创建 React 应用程序

首先,打开终端窗口,并导航到您想要构建项目的目录。

然后,使用create-react-app--template typescript旗帜:

1npx create-react-app cra-typescript-example --template typescript

您的终端窗口将显示一个初始消息:

1Creating a new React app in [..]/cra-typescript-example.
2
3Installing packages. This might take a couple of minutes.
4Installing react, react-dom, and react-scripts with cra-template-typescript...

「--template typcript」旗指示 Create React App 脚本使用 `cra-template-typescript' 模板构建,这将添加主 TypeScript 包

<$>[注] **注:**在以前的 Create React App 版本中,可以使用 --typescript 旗帜,但此选项已被删除。

一旦安装完成,您将有一个新的 React 应用程序,支持 TypeScript. 导航到您的项目目录,并在您的代码编辑器中打开它。

檢查「tsconfig.json」檔案

您可能已经注意到您的终端窗口显示了以下消息:

1We detected TypeScript in your project (src/App.test.tsx) and created a tsconfig.json file for you.
2
3Your tsconfig.json has been populated with default values.

tsconfig.json文件用于配置TypeScript项目,类似于package.json用于JavaScript项目。

由 Create React App 生成的 tsconfig.json 将看起来如下:

 1[label tsconfig.json]
 2{
 3  "compilerOptions": {
 4    "target": "es5",
 5    "lib": [
 6      "dom",
 7      "dom.iterable",
 8      "esnext"
 9    ],
10    "allowJs": true,
11    "skipLibCheck": true,
12    "esModuleInterop": true,
13    "allowSyntheticDefaultImports": true,
14    "strict": true,
15    "forceConsistentCasingInFileNames": true,
16    "noFallthroughCasesInSwitch": true,
17    "module": "esnext",
18    "moduleResolution": "node",
19    "resolveJsonModule": true,
20    "isolatedModules": true,
21    "noEmit": true,
22    "jsx": "react-jsx"
23  },
24  "include": [
25    "src"
26  ]
27}

此配置建立了多个编译规则和版本的 ECMAScript 来编译。

查看App.tsx文件

现在,让我们打开App.tsx文件:

 1[label src/App.tsx]
 2import React from 'react';
 3import logo from './logo.svg';
 4import './App.css';
 5
 6function App() {
 7  return (
 8    <div className="App">
 9      <header className="App-header">
10        <img src={logo} className="App-logo" alt="logo" />
11        <p>
12          Edit <code>src/App.tsx</code> and save to reload.
13        </p>
14        <a
15          className="App-link"
16          href="https://reactjs.org"
17          target="_blank"
18          rel="noopener noreferrer"
19        >
20          Learn React
21        </a>
22      </header>
23    </div>
24  );
25}
26
27export default App;

如果您以前曾使用过Create React App,您可能已经注意到,它与Create React App 生成的App.js文件非常相似,它用于非 TypeScript 构建。

接下来,让我们创建一个TypeScript组件,并探索它可以提供的优势。

创建一个 TypeScript 组件

首先,在App.tsx文件中创建一个功能组件:

1function MyMessage({ message }) {
2  return <div>My message is: {message}</div>;
3}

此代码将从props中取出一个消息值,它将返回一个div与文本我的消息是:消息值。

现在让我们添加一些TypeScript来告诉这个函数它的消息参数应该是字符串

如果你熟悉TypeScript,你可能会认为你应该尝试将消息:字符串附加到消息

您可以实现这一点的几种方法。

定义 inline 类型:

1function MyMessage({ message }: { message: string }) {
2  return <div>My message is: {message}</div>;
3}

定义一个props对象:

1function MyMessage(props: { message: string }) {
2  return <div>My message is: {props.message}</div>;
3}

使用单独的接口:

1interface MyMessageProps {
2  message: string;
3}
4
5function MyMessage(props: MyMessageProps) {
6  return <div>My message is: {props.message}</div>;
7}

您可以创建一个界面,并将其移动到一个单独的文件中,以便您的类型可以生活在其他地方。

这可能看起来像写很多,所以让我们看看我们从写下更多的东西中获得了什么。

我们已经告诉这个组件,它只接受一个字符串作为消息参数,现在让我们尝试在我们的应用组件中使用它。

使用 TypeScript 组件

让我们通过将它添加到渲染逻辑中来使用这个MyMessage组件。

开始键入组件:

1<MyMessage

如果您的代码编辑器支持代码暗示,您将注意到当您开始键入组件时,组件的签名将显示。

Screenshot of MyMessage's code signature.

这有助于为您提供预期值和类型,而无需返回组件,这在处理单独文件中的多个组件时尤为有用。

检测类型

现在,开始打印优惠:

1<MyMessage messa

一旦你开始键入消息,你就可以看到该是什么:

Screenshot of the expected message type.

显示(JSX属性)消息:字符串

检测错误类型

尝试将一个数字值传递给消息,而不是一个字符串:

1<MyMessage message={10} />

如果我们添加一个数字作为一个消息,TypeScript会引发一个错误,并帮助您捕捉这些打字错误。

Screenshot of TypeScript error that type number is not assignable to type string.

React 甚至不会编译,如果有类似此类的输入错误:

Screenshot of compilation error when running the app in a web browser.

這顯示「Type 'number' cannot be assigned to type'string'」。

结论

在本教程中,您将使用Create React App 设置一个 React 应用程序。

您可以为您的所有组件和特性创建类型,您可以利用现代代码编辑器进行代码提示,并且您将能够更快地捕捉错误,因为TypeScript甚至不会让项目编译类型错误。

如果您想了解更多关于 TypeScript 的信息,请参阅 我们的 TypeScript 主题页面以获取练习和编程项目。

Published At
Categories with 技术
comments powered by Disqus