(Introduction)
Create React App v2 introduced official TypeScript support, allowing JavaScript users to use TypeScript with the React front-end framework. TypeScript is a powerful tool that helps write safer, self-documenting code, allowing developers to catch bugs faster.
Create React App v2引入了官方TypeScript支持,从而允许JavaScript用户将TypeScript与React前端框架一起使用。 TypeScript是一个功能强大的工具,可帮助编写更安全的自文档代码,使开发人员可以更快地发现错误。
For this article, you will go through the steps of creating a React app with TypeScript using Create React App.
对于本文,您将完成使用Create React App使用TypeScript创建React应用的步骤。
(Starting a TypeScript Create React App)
First, let’s use create-react-app
with the --typescript
flag.
首先,让我们使用带有--typescript
标志的create-react-app
。
- npx create-react-app my-typescript-app --typescript
Let’s look at what packages the --typescript
flag get us and what changes it makes.
让我们看一下--typescript
标志为我们提供了哪些软件包以及它进行了哪些更改。
(The TypeScript Additions)
The --typescript
flag will add the main TypeScript package.
--typescript
标志将添加主TypeScript包 。
We also get this notice: We detected TypeScript in your project (src/App.test.tsx) and created a tsconfig.json file for you.
我们还会收到此通知: We detected TypeScript in your project (src/App.test.tsx) and created a tsconfig.json file for you.
The tsconfig.json
file is how we configure TypeScript projects, similar to how package.json
is for JS projects.
tsconfig.json
文件是配置TypeScript项目的方式,类似于package.json
用于JS项目的方式。
The default tsconfig.json
will look something like the following:
默认的tsconfig.json
如下所示:
{
"compilerOptions": {
"target": "es5",
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve"
},
"include": ["src"]
}
检查App.tsx
文件 (Examining the App.tsx
File)
Let’s jump into the main App file that usually is our main React component:
让我们进入通常是我们主要的React组件的主要App文件:
app.tsx
app.tsx
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
As you will notice, this is actually the same as the JavaScript App.js
. We get the same base as our JavaScript projects, but we can sprinkle TypeScript on top.
您将注意到,这实际上与JavaScript App.js
相同。 我们拥有与JavaScript项目相同的基础,但是我们可以将TypeScript撒在上面。
Next, let’s create a TypeScript component and see what benefits we can gain.
接下来,让我们创建一个TypeScript组件,看看我们可以获得什么好处。
(Creating a TypeScript Component)
We’ll start by creating a normal functional component in this same App.tsx
file:
我们将从在相同的App.tsx
文件中创建普通功能组件开始:
function MyMessage({ message }) {
return <div>i shall speak! my message is: {message}</div>;
}
This is a simple component where we pull message
out of props
. Now let’s add some TypeScript to tell this function that its message
parameter should be a string
.
这是一个简单的组件,我们从props
提取message
。 现在,让我们添加一些TypeScript来告诉该函数其message
参数应该为string
。
If you’re familiar with TypeScript, you may think you want to add the following to message: message: string
. What we have to do in this situation is define the types for all props
as an object. There’s a few ways we can do this:
如果您熟悉TypeScript,您可能会想将以下内容添加到message: message: string
。 在这种情况下,我们要做的就是将所有props
的类型定义为一个对象。 我们有几种方法可以做到这一点:
Types inline:
内联类型:
function MyMessage({ message }: { message: string }) {
return <div>i shall speak! my message is: {message}</div>;
}
Props object:
道具对象:
function MyMessage(props: { message: string }) {
return <div>i shall speak! my message is: {props.message}</div>;
}
Separate types object:
单独的类型对象:
interface MyMessageProps {
message: string;
}
function MyMessage({ message }: MyMessageProps) {
return <div>i shall speak! my message is: {props.message}</div>;
}
There are many ways to use TypeScript in our projects. You can create an interface
and move that into a separate file so your types can live elsewhere. This may seem like a lot of writing, so let’s see what we gain from writing a bit more.
在我们的项目中有多种使用TypeScript的方法。 您可以创建一个interface
并将其移到一个单独的文件中,以便您的类型可以放在其他地方。 这看起来好像是很多写作,所以让我们看看从多写一点中我们会得到什么。
We’ve told this component that it only accepts a string
as the message
parameter. Now let’s try using this inside our App
component.
我们已经告诉该组件它仅接受string
作为message
参数。 现在,让我们尝试在我们的App
组件中使用它。
(Using TypeScript Components)
Let’s use this MyMessage
component.
让我们使用这个MyMessage
组件。
When we go to use this component, we can see VS Code bring up the component’s signature right as we type. We don’t have to jump back to the component (especially if it’s in another file) to see what its inputs should be.
当我们使用该组件时,我们可以看到VS Code在键入时显示出该组件的签名。 我们不必跳回到组件(尤其是如果它在另一个文件中)来查看其输入内容。
That isn’t the most readable, so let’s jump into using each prop individually.
那不是最易读的,所以让我们跳入每个道具的单独使用。
(Seeing Prop Types)
As soon as we start typing message
, we can see what that prop should be:
一旦开始键入message
,我们就可以看到该道具应该是:
(Seeing Type Errors)
If we add a number as a message, TypeScript will throw an error and help us catch these typing bugs.
如果我们在消息中添加数字,TypeScript将引发错误并帮助我们捕获这些键入错误。
React won’t even compile if there are type errors like this:
如果存在如下类型错误,React甚至不会编译:
(Conclusion)
This only scratches the surface of what TypeScript provides us. You can create types for all your components and props, and with VS Code you’ll be able to read them. You’ll also catch errors faster since TypeScript won’t even let the project compile with type errors.
这只是TypeScript为我们提供的内容的起点。 您可以为所有组件和道具创建类型,使用VS Code,您将能够阅读它们。 由于TypeScript甚至不会让项目编译时遇到类型错误,因此您还将更快地捕获错误。
翻译自: https://www.digitalocean.com/community/tutorials/using-create-react-app-v2-and-typescript