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:

2 D铆as
17 Hrs
47 Min
7 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

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

3/26
Resources

TypeScript programming offers a robust and secure experience for developers looking to avoid common JavaScript errors. This programming language, which extends JavaScript with static typing, allows you to create more maintainable and scalable applications. Let's explore the basics to get started programming with TypeScript.

How to create your first "Hello world" program in TypeScript?

To start programming in TypeScript, the first thing we need to do is to create our classic "Hello World". This exercise will allow us to understand the basic process of compiling and executing TypeScript code.

First, we create a new file with extension .ts:

console.log("Hello world");

Once we have written our code, we need to compile it to convert it to JavaScript, since TypeScript does not run directly in browsers or in Node.js:

  1. Open the terminal
  2. Navigate to the folder where your file is
  3. Run the tsc command followed by the name of your file:
tsc main.ts

This command will generate an equivalent JavaScript file(main.js). To run it, we simply use Node.js:

node main.js

And we will see in the terminal our "Hello world" message. This compilation process is fundamental in TypeScript, as it transforms our code with types to pure JavaScript that can be interpreted by any environment.

What are typed variables in TypeScript?

The main feature of TypeScript is the type system. Unlike JavaScript, where variables can change type during execution, TypeScript allows us to explicitly define what type of data each variable will contain.

Let's look at some basic examples:

// String variablelet name: string = "min";
// Number variablelet age: number = 39;
// Boolean variablelet developer: boolean = true;
// Variable that can be undefined or stringlet month: undefined | string;
console.log(`Hello ${name}`);console.log(month); // Result: undefined
month = "january";console.log("updated month:", month); // Result: january

In the above example, we can see how we declare variables with different types:

  • name can only contain text
  • age can only contain numbers
  • developer can only be true or false
  • month can be a text string or be undefined

How to work with strings in TypeScript?

TypeScript offers different ways to work with text strings, similar to JavaScript. We can concatenate variables using the + operator or use template literals (string templates) with backticks (``).

let name: string = "min";
// Option 1: Traditional concatenationconsole.log("Hello " + name);
// Option 2: Template literals (recommended)console.log(`Hello ${name}`);

Both options produce the same result, but template literals are more readable when we work with long strings or need to insert multiple variables.

How do data types work in TypeScript?

TypeScript includes several basic data types that help us to clearly define the structure of our code:

  • string: For text
  • number: For numbers (integers and decimals)
  • boolean: For true/false values
  • undefined: For variables with no assigned value
  • null: For explicit null values

We can also create union types by combining several types with the | operator:

// This variable can be undefined or stringlet month: undefined | string;
console.log("initial month", month); // undefined
month = "January";console.log("updated month", month); // January.

In this example, month can contain text or be undefined. This is useful when a variable can have different types of values depending on the context.

How to experiment with TypeScript?

The best way to learn TypeScript is to experiment with different types of variables and observe how they behave. We recommend:

  1. Create variables with different types
  2. Try assigning incorrect values to see compilation errors.
  3. Using console.log() to visualize the values
  4. Compiling and executing the code to see the results

The TypeScript development process always includes these steps: write typed code, compile to JavaScript and execute the result. This cycle will help you become familiar with the language and its features.

Constant practice with these basic concepts will give you a solid foundation to move on to more complex TypeScript features. We encourage you to experiment with the examples shown and create your own variations to consolidate your learning. What other data types would you like to explore in TypeScript? Share your experiences in the comments!

Contributions 9

Questions 0

Sort by:

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

Los tipos de variables en TypeScript incluyen: 1. **string**: Cadenas de texto. 2. **number**: N煤meros, tanto enteros como decimales. 3. **boolean**: Valores de verdadero o falso. 4. **null**: Representa la ausencia de un valor. 5. **undefined**: Una variable que no ha sido asignada. 6. **any**: Permite cualquier tipo de valor. 7. **void**: Indica que no se devuelve ning煤n valor. 8. **never**: Representa valores que nunca ocurren. Estos tipos te permiten escribir c贸digo m谩s seguro y mantenible.
**5:42** 隆Falso! No es obligatorio tipar todas las variables expl铆citamente. TypeScript tiene **inferencia de tipos**, lo que significa que si asignas un valor a una variable al declararla, TypeScript puede inferir su tipo autom谩ticamente.
Por cierto, recientemente ya se puede ejecutar archivos `.ts` directamente desde Node.js con un flag (--). As铆: ```txt node --experimental-strip-types main.ts ``` <https://nodejs.org/en/learn/typescript/run-natively> Por otra parte Bun y Deno vienen con soporte a TypeScript por defecto, pero son entornos de ejecuci贸n distintos que han salido recientemente ;) <https://bun.sh> [https://deno.com](https://deno.com/)
**Node JS ha mejorado el soporte para Typescript** (Desde la Versi贸n de '22.0.70') el Flag `--experimental-strip-types` no permite la transformaci贸n de la sintaxis TypeScript no borrable, que requiere la generaci贸n de c贸digo JavaScript como" `enum` " para realizar esto podr铆as utilizando este flag en el momento de la ejecuci贸n: [`--experimental-transform-types`](https://nodejs.org/api/cli.html#--experimental-transform-types) <https://nodejs.org/api/typescript.html#full-typescript-support> La versi贸n LTS para esta fecha "v22.14.0" admite este soporte
![](https://static.platzi.com/media/user_upload/clase3-tipoPrimitivos-1-89184602-0252-45e2-b325-c778faa53c10.jpg) ![](https://static.platzi.com/media/user_upload/clase3-tipoPrimitivos-2-9c67687b-f1fc-428c-af4a-ebbd84cf6eae.jpg)
primer comentario XD
Pretty straighforward! B谩sicamente escribimos c贸digo tipado de TS, compilamos a JS y lo ejecutamos con Node.
### 馃摌 Tipos primitivos en TypeScript \---------------------------------------------------------------------------- ![](https://static.platzi.com/media/user_upload/image-a3b8d1d7-723a-4e19-8a2a-a734170462f5.jpg)
Hola, comparto el enlace del repositorio del curso en github [platzi/curso-typescript](https://github.com/platzi/curso-typescript)