Haga clic en la imagen para ir al curso de Scrimba
TypeScript ha ganado mucha popularidad entre los desarrolladores de JavaScript en los últimos años. Y no es de extrañar, ya que el código TypeScript tiende a ser menos propenso a errores, más legible y más fácil de mantener.
Así que nos hemos asociado con el eminente instructor en línea Dylan C. Israel y creamos un curso gratuito de TypeScript sobre Scrimba. El curso contiene 22 lecciones y es para personas que ya conocen JavaScript pero que desean una introducción rápida a TypeScript.
Haz el curso gratis aquí.
Ahora echemos un vistazo a cada una de las conferencias del curso.
Parte # 1: Introducción

En el screencast introductorio, Dylan ofrece una descripción general de por qué debería aprender TypeScript y cómo se presenta el curso. También te cuenta un poco sobre sí mismo, para que te familiarices con él antes de comenzar con la codificación.
Parte # 2: Tipos de variables
La verificación de tipo en tiempo de compilación es una de las características más importantes de TypeScript. Nos permite detectar errores relacionados con los tipos de datos en el momento de la compilación. Esta lección explica los tipos de datos disponibles en TypeScript.
let firstName: string; let age: number; let isMarried: boolean;
Puedes ver cómo tenemos tipos adjuntos a todas las variables. Si intentamos poner un valor de cadena en lugar de una variable de tipo numérico, TypeScript lo detectará en tiempo de compilación.
Parte # 3: Varios tipos
En TypeScript, mantenemos un solo tipo para una variable, pero eso no es posible siempre. Entonces, en cambio, TypeScript nos proporciona el any
tipo. Esto significa que podemos asignar varios tipos de valores a una variable.
let myVariable: any = 'Hello World'; myVariable = 10; myVariable = false;
Arriba, hemos declarado myVariable
con any
tipo. Primero le asignamos una cadena, luego un número y finalmente un booleano. Esto es posible debido al any
tipo.
Parte # 4: Subtipos
Los subtipos se utilizan cuando desconocemos el valor de la variable. TypeScript nos proporciona dos subtipos: null
y undefined
. Esta lección explica cuándo debemos usar cualquiera de esos.
let myVariable: number = undefined;
A la variable myVariable
se le ha asignado el valor de undefined
porque, en este momento, no sabemos cuál va a ser. También podemos usar null
aquí.
Parte # 5: mecanografía implícita vs explícita
La parte 5 habla sobre la diferencia entre escritura implícita y explícita. En los ejemplos anteriores, vimos tipos explícitos en los que establecemos el tipo de variable. La escritura implícita, por otro lado, la realiza el compilador sin que nosotros indiquemos el tipo de variable.
let myVariable = 'Hello World';
En este ejemplo, no hemos asignado ningún tipo a la variable. Podemos verificar el tipo de esta variable usando la typeof
función. Esto mostrará que myVariable
es de string
tipo porque el compilador se encargó de escribir.
Parte # 6: Tipos de cheques
En esta lección aprenderemos cómo podemos verificar el tipo de una variable y detectar cualquier error o realizar cualquier operación. Utiliza un ejemplo en el que probamos si nuestra variable es de tipo Bear
(donde Bear
es a class
). Si queremos verificar el tipo de nuestra variable, podemos usar el instanceof
método.
import { Bear } from 'somefile.ts'; let bear = new Bear(3); if (bear instanceof Bear) { //perform some operation }
Parte # 7: afirmaciones de tipo
La afirmación de tipo significa que podemos convertir una variable a cualquier tipo en particular y le decimos a TypeScript que maneje esa variable usando ese tipo. Intentemos entenderlo con un ejemplo:
let variable1: any = 'Hello World'; if ((variable1 as string).length) { //perform some operation }
variable1
tiene el tipo de any
. Pero, si queremos verificar su longitud, producirá un error hasta que le digamos a TypeScript que lo maneje como una cadena. Esta lección explica más detalles sobre este concepto.
Parte # 8: Matrices
Esta parte del curso explica las matrices de TypeScript. En JavaScript, cuando asignamos valores a una matriz, podemos colocar diferentes tipos de elementos. Pero, con TypeScript, también podemos declarar una matriz con tipos.
let array1: number[] = [1, 2, 3, 4, 5];
En el ejemplo anterior, declaramos una matriz de números asignándole el number
tipo. Ahora TypeScript se asegurará de que la matriz contenga solo números.
Parte # 9: Tuplas
A veces, necesitamos almacenar varios tipos de valores en una colección. Las matrices no servirán en este caso. TypeScript nos da el tipo de datos de las tuplas. Se utilizan para almacenar valores de varios tipos.
let tuple_name = [10, 'Hello World'];
Este ejemplo muestra que podemos tener elementos de datos de números y tipos de cadenas en una colección. Esta lección explica el concepto de tuplas con más detalle.
Parte # 10: enumeraciones
En esta lección, aprenderemos sobre las enumeraciones en TypeScript. Las enumeraciones se utilizan para definir un conjunto de constantes con nombre que se pueden utilizar para documentar la intención o para crear un conjunto de casos diferentes.
**enum** Direction { Up = "UP", Down = "DOWN", Left = "LEFT", Right = "RIGHT" }
Aquí hay un ejemplo básico de cómo se declaran las enumeraciones y cómo se crean diferentes propiedades dentro de ellas. El resto de los detalles se explican en esta sección del curso.
Parte # 11: Objeto
In JavaScript, objects have a pretty major role in how language has been defined and has evolved. This lesson talks about objects in TypeScript — how to declare an object, and which kinds of values can fit inside the object type.
Part #12: Parameters
Using TypeScript, we can also assign types to the parameters of a function. In this section of the course, Dylan explains how we can add types to parameters. This is a very useful way to handle errors regarding data type in a function.
const multiply = (num1: number, num2: number) => { return num1 * num2; }
We have declared a function multiply
which takes two parameters and returns the value from multiplying them. We added a type of number
to both the parameters so that no other value except a number can be passed to them.
Part #13: Return types
Like parameters, we can also add type-checking to the return value of a function. This way we can make sure that the return value from a function has an expected type. This part of the course explains the concept in detail.
const multiply = (num1: number, num2: number): number => { return num1 * num2; }
We have added a return
type of number
to the function. Now, if we return anything except a number
, it will show us an error.
Part #14: Custom types
In TypeScript, we can create a custom type using the keyword of type.
We can then type-check objects on the basis of that type.
type person = {firstName: string}; const example3: person = {firstName: 'Dollan'};
This feature is almost deprecated in TypeScript, so you should rather use interface
or class
for this purpose. However, it’s important that you get to know it, as you might come across custom types when you start to dive into TS code.
Part #15: Interfaces
In TypeScript, the core focus is on type-checking which enforces the use of a particular type. Interfaces are a way of naming these types. It’s basically a group of related methods and properties that describe an object. This part of the course explains how to create and use interfaces.
interface Person { firstName: string, lastName: string, age: number }
In the example above, we have an interface Person
which has some typed properties. Note that we don’t initiate data in interfaces, but rather define the types that the parameters will have.
Part #16: Barrels
A barrel is a way to rollup exports from multiple modules into a single module. A barrel is, itself, a module, which is exporting multiple modules from one file. This means that a user has to import just one module instead of all the modules separately.
// Without barrel import { Foo } from '../demo/foo'; import { Bar } from '../demo/bar'; import { Baz } from '../demo/baz';`
Instead of using these multiple lines separately to import these modules, we can create a barrel. The barrel would export all these modules and we import only that barrel.
// demo/barrel.ts export * from './foo'; // re-export all of its exportsexport * from './bar'; // re-export all of its exportsexport * from './baz'; // re-export all of its exports
We can simply create a TypeScript file and export the modules from their respective file. We can then import this barrel wherever we need it.
import { Foo, Bar, Baz } from '../demo'; // demo/barrel.ts
Part #17: Models
When using interfaces, we often face a number of problems. For example, interfaces can’t seem to enforce anything coming from the server side, and they can't keep the default value. To solve this issue, we use the concept of models classes. These act as an interface, and also may have default values and methods added to them.
Part #18: Intersection types
In this section, we’ll talk about intersection types. These are the ways we can use multiple types to a single entity or class. Sometimes we need to use multiple types to map one entity and, at that time, this feature comes in very handy.
import { FastFood, ItalianFood, HealthyFood} from ‘./interfaces’; let food1: FastFood | HealthyFood; let food2: ItalianFood; let food3: FastFood; let food4: FastFood & ItalianFood;
In the example above, we have three interfaces and we are creating different objects from them. For example, food1
is going to be either FastFood
orHealthyFood
. Similarly, food4
is going to be FastFood
as well asItalianFood
.
Part #19: Generics
In short, generics is a way to create reusable components which can work on a variety of data types rather than a single one.
The concept of generics is actually not available in JavaScript so far, but is widely used in popular object-oriented languages such as C# or Java. In this lesson, we’ll learn how to use generics in TypeScript, and look at its key benefits.
Part #20: Access modifiers
The idea of access modifiers is relatively new in the arena of JavaScript and TypeScript, but they have been available in other object-oriented languages for a long time. Access modifiers control the accessibility of the members of a class.
In TypeScript, there are two access modifiers: public and private. Every member of a class defaults to public until you declare it otherwise.
class Customer { customerId: number; public companyName: string; private address: string; }
customerId
is a default public member, so it’s always available to the outside world. We have specifically declared companyName
aspublic
, so it will also be available outside of class. address
is marked as private,
therefore it won’t be accessible outside the class.
Part #21: Local setup
In this lesson, we’ll learn the steps to install and run TypeScript on local computers. Those steps generally involve installing Node and TypeScript, and then compiling “.ts” files.

Click the image to get to the course.
Part #22: TSLint and — great job!
Yay! You’ve completed the course. In the last part of the video, Dylan will give some tips on how to take this learning further and improve the code we write today.
En esta lección, también explica cómo puede utilizar el increíble TSLint. Esta herramienta le ayuda a escribir un mejor código de nivel de producción utilizando las mejores prácticas y convenciones. Viene con algunas configuraciones básicas que puede modificar para satisfacer sus necesidades.
¡Así que sigue adelante y realiza este curso gratuito hoy!
¡Gracias por leer! Mi nombre es Per Borgen, soy el cofundador de Scrimba, la forma más fácil de aprender a codificar. Debe consultar nuestro bootcamp de diseño web receptivo si desea aprender a construir un sitio web moderno a nivel profesional.
