As a statically typed programming language, TypeScript can do type annotations and type inference. It checks the type of a variable at compile time. For error correction at compile time. This article analyzes the application of TS in creation-React-app based on the TSX file I used in a CRA project.

Make CRA support TypeScript

Use webstorm or VScode to open the project folder, open the terminal and run the following command:

yarn global add create-react-app
create-react-app . --template typescript
Copy the code

Variable types and variable declarations

The following code exists in the TSX file.

type Category = "-" | "+"     
const defaultFormData = {
    tagIds: [] as number[].note: "".category: The '-' as Category,
    amount: 0
}
Copy the code

Let’s do it line by line. In TS, there are several ways to declare a type. The most commonly used are type(alias) and interface(interface). In short, type is an advanced type of TS. It can include intersections of various types, such as

; The joint, such as the type in the code above Category = “-” | “+”. It can also be used to define raw data types. Interfaces are properties and methods that describe an object and are used to define object types.

Type inference

Again, tagIds: [] as number[] is type inference. This code defines the type of tagIds as an array with each entry as a number.

TS function

const onChange = (obj: Partial<typeof selected>) = >{ setSelected({ ... selected, ... obj }) }Copy the code

In the TS function, you need to declare the type of the argument. You can also use the extension operator… Rest to declare the types of the remaining parameters.

TS generic

In the code above, generics are defined in <>. Generics are when you write code in strongly typed programming languages that uses types you specify later. It gives developers the ability to have flexible, reusable code. It is commonly used to declare the types of functions, interfaces, and classes.

Another example:

const [category, setCategory] = useState<The '-' | '+'> ("-")
Copy the code

Is equivalent to

type Category = "-" | "+"  
const [category, setCategory] = useState<Category>("-")
Copy the code

The React function of type

type Props = {
    value: number[];
    onChange: (selected: number[]) = > void;
}

const TagsSection: React.FC<Props> = (props) = >{... }Copy the code

In the React function component, define the function component as functions of type react. FC and its generic type as Props. The props parameter also has properties of the props type. That’s inheritance.

Attach the project preview address and source address.