Fundamentos de TypeScript

1

¿Qué es TypeScript y por qué usarlo?

2

Instalación de Node.js y TypeScript CLI, configuración de tsconfig.json

3

Tipos primitivos: string, number, boolean, null, undefined de Typescript

4

Tipos especiales: any, unknown, never, void de TypeScript

5

Arrays, Tuplas, Enums en TypeScript

Funciones e Interfaces

6

Declaración de funciones, tipado de parámetros y valores de retorno

7

Parámetros opcionales, valores por defecto y sobrecarga de funciones

8

Creación y uso de interfaces de TypeScript

9

Propiedades opcionales, readonly, extensión de interfaces en TypeScript

Clases y Programación Orientada a Objetos

10

Creación de clases y constructores En TypeScript

11

Modificadores de acceso (public, private, protected) en Typescript

12

Uso de extends, sobreescritura de métodos en TypeScript

13

Introducción a Genéricos en Typescript

14

Restricciones con extends, genéricos en interfaces

Módulos y Proyectos

15

Importación y exportación de módulos en TypeScript

16

Agregando mi archivo de Typescript a un sitio web

17

Configuración de un proyecto Web con TypeScript

18

Selección de elementos, eventos, tipado en querySelector en TypeScript

19

Crear un proyecto de React.js con Typescript

20

Crea un proyecto con Angular y Typescript

21

Crea una API con Typescript y Express.js

Conceptos Avanzados

22

Introducción a types en TypeScript

23

Implementación de Decoradores de TypeScript

24

Async/await en Typescript

25

Pruebas unitarias con Jest y TypeScript

26

Principios SOLID, código limpio, patrones de diseño en Typescript

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
14 Hrs
12 Min
16 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

Crear un proyecto de React.js con Typescript

19/26
Resources

The creation of modern web applications has been greatly simplified thanks to frontend development frameworks. These frameworks allow us to build interactive and dynamic interfaces more easily, reducing configuration time and allowing us to focus on what really matters: business logic and user experience. React, developed by Facebook, has positioned itself as one of the most popular and powerful frameworks on the market, especially when combined with TypeScript for more robust development with fewer bugs.

How to create a React project with TypeScript?

React is a leading framework in frontend development that allows you to create interactive user interfaces efficiently. Combining it with TypeScript gives us additional advantages such as static typing, which reduces errors in development time. Creating a project that integrates both technologies is surprisingly easy thanks to tools like Vite.

To start a React project with TypeScript, we follow these steps:

  1. We open VS Code and create a folder for our project.
  2. Open the terminal and go to the created folder.
  3. Run the command: npm create vite@latest.
  4. We follow the interactive wizard to configure our project.

The wizard will ask for basic information such as

  • Project name
  • Package name
  • Framework to use (we select React)
  • Variant (we select TypeScript + SWC for better performance)

Once this process is completed, we will have a project framework ready to start developing. The magic of these templates is that all the complex configuration is already done for us, allowing us to concentrate on writing productive code right out of the box.

Structure and execution of the generated project

After creating the project, we will find an organized file structure that includes:

  • Folder src: contains the source code of our application.
  • Public folder: for static files
  • Configuration files such as package.json and tsconfig.json

To start our project, we must:

# move to the project foldercd project-name
 # install dependenciesnpm install
 # start the development servernpm run dev

By executing these commands, our project will be available at a local address (usually http://localhost:5173/) and we will be able to see a welcome page with a working counter.

What are TSX files and how do they work?

One of the peculiarities of working with React and TypeScript is the .tsx file extension. This special extension combines TypeScript with JSX (JavaScript XML), allowing us to write HTML code directly inside our TypeScript files.

If we explore the App.tsx file generated in our project, we will see code like this:

import { useState } from 'react'import reactLogo from './assets/react.svg'import './App.css'
function App() { const [counter, setCounter] = useState(0)
 return (<div className="App">
        <h1>Platzitemplate</h1>
        <div className="card">
          <button onClick={() => setCounter((counter) => counter + 1)}>
 counter: {counter}
         </button>
       </div>
     </div> )}
export default App.

This file shows the JSX syntax, where we can write HTML elements like <div>, <h1> and <button> directly in our TypeScript code. The magic happens when we modify this file: the changes are instantly reflected in the browser thanks to the hot reloading provided by Vite.

TypeScript configuration in the project

The generated project includes configuration files specific to TypeScript:

  • tsconfig.json: the main file that references other configuration files.
  • tsconfig.app.json: application-specific settings
  • tsconfig.node.json: configuration for Node.js environment

These files contain the TypeScript compiler options(compilerOptions) that determine how our code is compiled. The advantage of using a template is that these settings are already optimized to work with React, saving us from having to configure them manually.

How does the compilation process work?

The compilation process in a React project with TypeScript is automated thanks to the scripts defined in the package.json file. When we run npm run dev, a process chain is triggered which:

  1. Starts the Vite development server
  2. Compiles the TypeScript/TSX files to JavaScript
  3. Serves the application on a local server
  4. Watches for changes in the files to automatically recompile

The tsc (TypeScript Compiler) command is responsible for transforming our TypeScript code into JavaScript that the browser can understand. This process is configured in the build script of the package.json:

"scripts": { " dev": "vite", " build": "tsc && vite build", " preview": "vite preview"}

The beauty of this system is that everything happens transparently to the developer. We don't need to worry about manually running the compiler or configuring additional tools.

Templates like the one we've created allow us to quickly get started with a React and TypeScript project without having to deal with the initial setup. We can customize this base to our specific needs, adding or removing components and functionality. This approach saves us valuable time that we can spend on developing the unique features of our application instead of setting up the development environment.

Have you tried creating projects with React and TypeScript? What other templates or tools have you found useful to speed up your workflow? Share your experience in the comments.

Contributions 3

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

💡 \*\*¿Qué significa la opción "TypeScript + SWC" al crear un proyecto con Vite?\*\* Cuando eliges \*\*TypeScript + SWC\*\*, estás configurando tu proyecto para usar: ✅ \*\*TypeScript\*\* como lenguaje principal. ✅ \*\*SWC\*\* (\*Speedy Web Compiler\*) como el compilador/transpiler en lugar de Babel o TSC. 🔹 \*\*¿Qué es SWC?\*\* SWC es un compilador escrito en \*\*Rust\*\*, diseñado para ser \*\*rápido y eficiente\*\*. Se usa en lugar de Babel o el compilador de TypeScript para mejorar el rendimiento. 🔹 \*\*Ventajas de usar SWC en Vite:\*\* ⚡ \*\*Mayor velocidad\*\* en la transpilación. 🖥️ \*\*Menor consumo de recursos\*\* en comparación con Babel o TSC. 📜 \*\*Compatible con TypeScript\*\*, pero \*\*NO hace verificación de tipos\*\* (solo transpila). 🔹 \*\*¿Cuándo elegir esta opción?\*\* Si necesitas una \*\*transpilación rápida\*\* y puedes manejar la verificación de tipos con `tsc --noEmit` o un IDE como VSCode. 🚀 ¡Espero que esto aclare la duda! 😊
Les recomiendo mucho usar TypeScript con Astro.js es lo mejor
Para crear un proyecto de React con TypeScript, sigue estos pasos: 1. **Abre tu terminal**: Navega a la carpeta donde deseas crear tu proyecto. 2. **Ejecuta el comando**: Escribe el siguiente comando: ``` npx create-react-app nombre-del-proyecto --template typescript ``` Esto usará `create-react-app` para configurar un nuevo proyecto de React con TypeScript. 3. **Accede a la carpeta del proyecto**: ``` cd nombre-del-proyecto ``` 4. **Instala las dependencias**: Asegúrate de que estás en la carpeta del proyecto y ejecuta: ``` npm install ``` 5. **Inicia el servidor de desarrollo**: Finalmente, ejecuta: ``` npm start ``` Esto abrirá tu nueva aplicación en el navegador. Ahora tienes un proyecto de React configurado para usar TypeScript. Puedes empezar a desarrollar haciendo modificaciones en los archivos dentro de la carpeta `src`.