Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript + React in Practice

TypeScript + React in Practice

TypeScript provides complete type support for React development, improving code reliability.

Using TypeScript gives React components, Props, State, etc. complete type checking, reducing runtime errors.

View the React tutorial:https://www.runoob.com/vue3/react-tutorial.html


React + TypeScript type support React components React.FC interface ButtonProps { text: string React Hooks useState(initial) useEffect(() => {}, []) useCallback(fn) Event Handling React.FormEvent React.ChangeEvent React.MouseEvent Advantages of TypeScript Compile-time type checking Smart code completion Safer refactoring

Why use TypeScript in React

React component-based development produces large amounts of data flows such as Props, State, and Context.

Without type definitions, it is hard to trace the source and structure of data, and runtime errors are likely.

TypeScript provides React with a complete type system: component Props have type checking, useState has type inference, and event handling has type hints.

Data flow:Data flow in React (Props, State, Context) all need type definitions; TypeScript can ensure the type safety of data flow.


Create project

Use a modern scaffold to create a React project with TypeScript support.

Initialization

Use Create React App (slower but complete)

npx create

react

app my

app

--

template typescript

Or use Vite (recommended, faster)

npm create vite

@

latest my

app

--

--

template react

ts

Recommended:Vite is currently the most recommended React build tool, with fast speed and a good development experience.


Component types

Use the React.FC type to define function components.

src/components/Button.tsx

import

React from

"react"

;

// Define the Props type for the button component

interface

ButtonProps

{

    text

:

string

;

                   

// Button text (required)

    onClick

:

(

)

=>

void

;

           

// Click callback (required)

    disabled

?:

boolean

;

             

// Whether disabled (optional, default false)

    variant

?:

"primary"

|

"secondary"

;

// Button variant (optional)

}

// Use React.FC to define the function component type

const

Button

:

React.

FC

<

ButtonProps

=

(

{

text

,

onClick

,

disabled

=

false

,

variant

=

"primary"

}

)

=>

{

return

(

<

button

className

=

{

`btn btn

$

{

variant

}

`

}

            onClick

=

{

onClick

}

            disabled

=

{

disabled

}

       

           

{

text

}

       

button

   

)

;

}

;

export

default

Button

;

Running result:

Button 组件渲染成功

React.FC:This is the type of a React function component, including built-in types such as children and propTypes.


Props types

Define the Props interface for a component to pass data to child components.

src/components/UserCard.tsx

import

React from

"react"

;

// Define the user type

interface

User

{

    id

:

number

;

         

// The user ID

    name

:

string

;

       

// Username

    email

:

string

;

     

// Email

    avatar

?:

string

;

   

// Avatar (optional)

}

// Define the Props for the user card component

interface

UserCardProps

{

    user

:

User

;

                     

// User object (required)

    onEdit

:

(

user

:

User

)

=>

void

;

   

// Edit callback

    onDelete

:

(

id

:

number

)

=>

void

;

 

// Delete callback

}

const

UserCard

:

React.

FC

<

UserCardProps

=

(

{

user

,

onEdit

,

onDelete

}

)

=>

{

return

(

<

div className

=

"user-card"

           

{

user.

avatar

&&

<

img src

=

{

user.

avatar

}

alt

=

{

user.

name

}

/>

}

           

<

h3

{

user.

name

}

h3

           

<

p

{

user.

email

}

p

           

<

button onClick

=

{

(

)

=>

onEdit

(

user

)

}

Editing

button

           

<

button onClick

=

{

(

)

=>

onDelete

(

user.

id

)

}

Delete

button

       

div

   

)

;

}

;

export

default

UserCard

;

**Type passing:** Pass types through Props to ensure consistent data types across the entire component tree.


useState types

Provide a type parameter for useState to ensure the state type is correct.

src/components/Counter.tsx

import

React

,

{

useState

}

from

"react"

;

const

Counter

:

React.

FC

=

(

)

=>

{

   

// Basic type: explicitly specify the number type

   

const

[

count

,

setCount

]

=

useState

<

number

(

0

)

;

   

// Object type: specify the object type

   

const

[

user

,

setUser

]

=

useState

<

{

name

:

string

;

age

:

number

}

(

{

        name

:

"Alice"

,

        age

:

25

   

}

)

;

   

return

(

       

<

div

<

p

Count

:

{

count

}

p

           

<

button onClick

=

{

(

)

=>

setCount

(

c

=>

c

1

)

}

1

button

           

<

button onClick

=

{

(

)

=>

setCount

(

c

=>

c

1

)

}

1

button

           

<

p

User

:

{

user.

name

}

,

{

user.

age

}

p

           

<

button onClick

=

{

(

)

=>

setUser

(

{

...

user

,

age

:

user.

age

1

}

)

}

                Age

1

           

button

       

div

   

)

;

}

;

export

default

Counter

;

Running result:

Counter 组件渲染成功

Generic parameter:useState The T in it is the type of the state; if an initial value is provided, TypeScript can infer it automatically.


useEffect types

useEffect also has complete type support.

src/components/DataFetcher.tsx

import

React

,

{

useState

,

useEffect

}

from

"react"

;

// Define the user type

interface

User

{

    id

:

number

;

    name

:

string

;

}

const

DataFetcher

:

React.

FC

=

(

)

=>

{

   

// User list state

   

const

[

users

,

setUsers

]

=

useState

<

User

[

]

(

[

]

)

;

   

// Loading state

   

const

[

loading

,

setLoading

]

=

useState

<

boolean

(

true

)

;

   

// Error state

   

const

[

error

,

setError

]

=

useState

<

string

|

null

(

null

)

;

    useEffect

(

(

)

=>

{

       

// Simulate fetching data

        fetch

(

"/api/users"

)

            .

then

(

res

=>

res.

json

(

)

)

            .

then

(

data

=>

{

                setUsers

(

data

)

;

                setLoading

(

false

)

;

           

}

)

            .

catch

(

err

=>

{

                setError

(

err.

message

)

;

                setLoading

(

false

)

;

           

}

)

;

   

}

,

[

]

)

;

 

// Empty dependency array: execute only once when the component mounts

   

if

(

loading

)

return

<

div

Loading...

div

;

   

if

(

error

)

return

<

div

Error

:

{

error

}

div

;

   

return

(

       

<

ul

{

users.

map

(

user

=>

(

               

<

li key

=

{

user.

id

}

{

user.

name

}

li

           

)

)

}

       

ul

   

)

;

}

;

export

default

DataFetcher

;

Dependency array:The second parameter of useEffect is the dependency array; TypeScript checks whether all variables used in the callback are declared in the array.


Event Handling

React events have dedicated type definitions.

src/components/Form.tsx

import

React

,

{

useState

}

from

"react"

;

const

Form

:

React.

FC

=

(

)

=>

{

   

// String-type state

   

const

[

name

,

setName

]

=

useState

<

string

(

""

)

;

   

// Form submit event handler

   

const

handleSubmit

=

(

e

:

React.

FormEvent

<

HTMLFormElement

)

=>

{

        e.

preventDefault

(

)

;

 

// Prevent the form's default submission

        console.

log

(

"Submit:"

,

name

)

;

   

}

;

   

// Input box change event handler

   

const

handleChange

=

(

e

:

React.

ChangeEvent

<

HTMLInputElement

)

=>

{

setName

(

e.

target

.

value

)

;

   

}

;

   

return

(

       

<

form onSubmit

=

{

handleSubmit

}

           

<input type="text" value={name}onChange={handleChange}placeholder=>

"Enter name"

           

/>

           

<

button type

=

"submit"

Submit

button

       

form

   

)

;

}

;

export

default

Form

;

Running result:

Form 组件渲染成功

Event types:React provides a type for every DOM event, such as FormEvent, ChangeEvent, MouseEvent, etc.


Notes

Best practices:Put type definitions and components in the same file, or manage them centrally in a types directory.


Summary

TypeScript greatly improves the React development experience.

Note:Using TypeScript directly in new projects can significantly reduce runtime errors.