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
47 Min
52 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

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

4/26
Resources

Programming with TypeScript offers a more robust development experience thanks to its static typing system. While JavaScript allows for greater flexibility, TypeScript provides additional safety by detecting errors during compilation. Exploring advanced variable types in TypeScript is essential to get the most out of this language and create more robust and maintainable applications.

What are advanced variable types in TypeScript?

After becoming familiar with basic TypeScript types such as string, number and boolean, it is time to explore more advanced types that offer additional functionality. These special types allow us to handle particular situations in our code and are powerful tools when used correctly.

How does the any type work?

The any type is probably the most flexible type in TypeScript, since it allows us to assign any type of value to a variable. To declare a variable of type any, we use the following syntax:

let variableAny: any;

Once declared, we can assign different types of values to it without restrictions:

variableAny = "hello"; // Text stringvariableAny = 42; // NumbervariableAny = true; // Boolean.

It is important to note that using any eliminates the advantages of the TypeScript type system, since we are basically telling the compiler to ignore the type of this variable. For this reason, it is recommended to limit its use to situations where it is really necessary.

What is the unknown type used for?

Type unknown is similar to any, but with a crucial difference: it is safer. A variable of type unknown can receive any value, but we cannot perform operations with it without first checking its type:

let variableUnknown: unknown;
variableUnknown = "hello";// variableUnknown = 42;// variableUnknown = true;
if (typeof variableUnknown === "string") { console.log("Variable unknown is a string:", variableUnknown);}

The main advantage of unknown over any is that it forces us to perform type checks before using the variable, which reduces the possibility of runtime errors.

When to use the never type in functions?

The never type is used for functions that never return a value, usually because:

  • They throw an exception
  • Have an infinite loop
  • They terminate the program

A common case is for functions that throw errors:

function throwError(message: string): never { throw new Error(message);}
// throwError("This is an error");

The never type is particularly useful for handling error cases in complex applications and for ensuring that certain parts of the code never execute normally.

What does the void type represent?

The void type is mainly used for functions that do not return any value, but do terminate their execution normally (unlike never):

function logMessage(message: string): void { console.log(message); // No return}
logMessage("This is a log message");

The function with void type can execute code and terminate normally, but does not return any usable value. It is common in functions that perform some action but do not need to return information.

How to choose the right type for each situation?

Choosing the right type depends on the context and specific needs:

  • Use any when you really can't predict the type (although it's best to avoid it when possible).
  • Prefer unknown over any when you need flexibility but want to maintain type safety.
  • Use never for functions that throw exceptions or never terminate.
  • Apply void for functions that perform actions but do not return values.

Constant practice with these types will help you become familiar with their peculiarities and use them effectively in your TypeScript projects.

Understanding these advanced variable types in TypeScript is critical to developing robust and maintainable applications. We invite you to experiment with these concepts, intentionally cause errors, and learn from them. What other TypeScript types would you like to explore? Share your experiences in the comments.

Contributions 8

Questions 1

Sort by:

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

**Es importante destacar que usar any elimina las ventajas del sistema de tipos de TypeScript**. ![](https://static.platzi.com/media/user_upload/image-dd1eb232-df0e-42c3-bd25-9cca17bfc3dc.jpg)
## 馃弳 **Cu谩ndo usar cada uno** * Usa `void` cuando **no necesitas devolver un valor significativo**. * Usa `never` cuando **una funci贸n nunca termina de manera normal**.
en conclusi贸n decimos: 1. `never` devuelve valores como mensajes de errores o bucles infinitos 2. `void` devuelve console.log o undefined (valores no utiles) 3. Usamos `unknown` antes que `any` en la mayor铆a de casos
Los tipos de variables en TypeScript tienen prop贸sitos espec铆ficos, aunque se parezcan, sus casos de uso pueden variar: 1. **any**: Permite asignar cualquier tipo de valor. 脷til cuando no se tiene certeza del tipo, pero a costa de perder la verificaci贸n de tipos. 2. **unknown**: Similar a `any`, pero m谩s seguro; requiere realizar una verificaci贸n de tipo antes de usar el valor. Ideal para manejar datos que provienen de fuentes externas, donde no se conoce su tipo. 3. **void**: Se utiliza en funciones que no devuelven un valor. Esencial para describir funciones que solo realizan efectos secundarios. 4. **never**: Se utiliza en funciones que nunca terminan. 脷til para manejar excepciones. Usa `unknown` cuando trabajes con tipos din谩micos, `void` en funciones sin retorno, y `never` en funciones que pueden arrojar errores o que nunca finalizan. Y evita usar `any` en la medida de lo posible.
En TypeScript, `never` y `void` son tipos de retorno de funciones, pero tienen prop贸sitos distintos: - **never**: Indica que una funci贸n nunca regresar谩 un valor, generalmente porque lanza un error o tiene un bucle infinito. Es utilizado en funciones que no terminan normalmente. - **void**: Significa que una funci贸n no devuelve ning煤n valor. Se usa en funciones que ejecutan acciones pero no necesitan devolver un resultado. En resumen, usa `never` cuando la funci贸n nunca termina y `void` cuando la funci贸n termina sin devolver un valor.
El tipo `unknown` en TypeScript se utiliza para representar valores cuyo tipo es desconocido en el momento de la compilaci贸n. A diferencia de `any`, que permite asignar cualquier tipo de valor sin restricciones, `unknown` obliga al desarrollador a realizar verificaciones de tipo antes de operar con la variable. Esto brinda mayor seguridad en el manejo de datos. **Comparativa:** - **any**: Se puede asignar cualquier tipo de valor y no se realizan verificaciones de tipo. Puede llevar a errores en tiempo de ejecuci贸n si se utilizan valores inesperados. - **unknown**: Permite asignar cualquier tipo de valor, pero requiere verificar su tipo antes de realizar operaciones. Esto ayuda a evitar errores y mejora la seguridad del c贸digo. Ambos tipos son 煤tiles, pero `unknown` es preferible cuando se requiere m谩s control sobre el tipo de datos que se maneja.
![](https://static.platzi.com/media/user_upload/imagen-d7552cb9-1400-42fb-b0c7-6f55a6597ab6.jpg) como un comod铆n
`any`, `unknown`, `never` y `void` son tipos especiales en TypeScript que ayudan a manejar datos de diferentes maneras. 1. **any**: Este tipo permite asignar cualquier tipo de dato a una variable. Por ejemplo, puedes tener `let variable: any;`, y luego asignarle un string, un n煤mero o un booleano. Esto es 煤til cuando no te importa el tipo, pero puede llevar a errores si no se controla adecuadamente. 2. **unknown**: Similar a `any`, pero m谩s seguro. Cuando declaras una variable de tipo `unknown`, no puedes usarla directamente sin comprobar su tipo primero. Esto obliga a realizar validaciones, proporcionando una mayor seguridad en el c贸digo. 3. **never**: Indica que una funci贸n no devolver谩 un valor. Por ejemplo, al lanzar un error, se puede declarar una funci贸n con tipo `never`. Esto es 煤til para indicar que el flujo del c贸digo no continuar谩 despu茅s de una operaci贸n fallida. 4. **void**: Se utiliza principalmente en funciones que no devuelven ning煤n valor. Por ejemplo, `function logMessage(message: string): void { console.log(message); }` indica que la funci贸n solo ejecutar谩 su tarea sin devolver un resultado. Estos tipos permiten a los desarrolladores crear aplicaciones m谩s robustas y mantener un control m谩s estricto sobre los tipos de datos en su c贸digo.