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
5 Hrs
17 Min
40 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

Creaci贸n y uso de interfaces de TypeScript

8/26
Resources

The implementation of interfaces in TypeScript represents a powerful tool that, although it may initially appear complex, offers extraordinary flexibility in application development. Interfaces allow you to define data structures and behaviors that can be easily reused, creating more maintainable and scalable code. Let's discover how to take advantage of this fundamental feature of the language to improve our projects.

What are interfaces in TypeScript and why are they so flexible?

Interfaces in TypeScript are contracts that define the structure that an object or function should have. Unlike classes, interfaces can be more easily extended and transferred between different files, which makes them extremely versatile.

One of the main advantages of interfaces is that they allow defining both properties and methods, providing a complete way of modeling objects and behaviors. This feature makes them ideal tools for creating reusable and well-structured code.

To implement a basic interface in TypeScript, we use the reserved word interface followed by the name we want to assign to it:

interface Person { name: string; age: number; isDeveloper: boolean;}

This interface defines that any object of type Person must have three properties: name (string), age (number) and isDeveloper (boolean).

How to use interfaces for individual objects?

Once an interface is defined, we can create objects that implement it. This ensures that these objects comply with the defined structure:

let person: Person = { name: "John", age: 30, isDeveloper: true};
console.log(person);

When executing this code, we will see in the console the object with the defined properties. TypeScript will check at compile time that the object complies with the interface structure, which helps prevent errors.

How to work with collections of interfaces?

Interfaces can also be used to define arrays of objects that share the same structure:

let people: Person[] = [ { { name: "John", age: 30, isDeveloper: true }, { name: "Mary", age: 25, isDeveloper: false }];
console.log(people);

This code creates an array of objects that implement the Person interface. When executed, we will see in the console all the elements of the array.

How to define methods in interfaces?

A powerful feature of interfaces is the ability to define methods that must be implemented by the objects that use them:

interface Sumar { sum(a: number, b: number): number;} }
let sum: Sumar = { sum(a: number, b: number): number { return a + b; } } };
console.log(sum.sum(3, 5)); // Result: 8.

In this example, the Sum interface defines a method called sum that receives two numeric parameters and returns a number. Then, we create an object that implements this interface by providing the implementation of the method.

Why use interfaces for methods?

Although it may seem a bit bureaucratic to define methods through interfaces, this practice offers several advantages:

  1. Consistency: It ensures that all objects that implement the interface have the same methods with the same signatures.
  2. Documentation: Interfaces act as clear documentation of what is expected of an object.
  3. Flexibility: Different classes or objects can implement the same interface in different ways.

How to combine properties and methods in interfaces?

One of the great advantages of interfaces in TypeScript is that they can combine both properties and methods in the same definition:

interface Person { name: string; age: number; isDeveloper: boolean; describe(): string; isMayor(): boolean;}

This interface defines not only the properties of a person, but also methods that can provide additional information about it. This ability to combine properties and behaviors makes interfaces extremely versatile tools.

Interfaces in TypeScript are fundamental tools that allow you to create more structured, reusable, and maintainable code. Although they may seem complex at first, once you understand how they work, they become indispensable allies in the development of robust applications. Have you used interfaces in your projects? Share your experience and how they have improved your code in the comments.

Contributions 2

Questions 1

Sort by:

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

Luego de un tiempo trabajando con typescript, creo que se cre贸 una mala costumbre de como utilizar las interfaces. En lo personal creo que cuando queremos tipar alguna estructura, ya sea un array o un objeto, lo correcto es utilizar type, y dejar las interfaces para OOP.
Las interfaces, enums y tipos literales en TypeScript tienen similitudes pero cumplen diferentes roles. - **Interfaces**: sirven para definir la forma de un objeto, describiendo sus propiedades y m茅todos. Son extensibles y permiten crear estructuras complejas. - **Enums**: son una forma de definir un conjunto de constantes relacionadas. Facilitan la lectura de c贸digo al usar nombres en lugar de valores num茅ricos o cadenas. - **Tipos literales**: permiten definir un tipo exacto para una variable o propiedad, restringiendo los valores a un conjunto espec铆fico. As铆, aunque comparten la capacidad de definir tipos, cada uno tiene un prop贸sito distinto en la programaci贸n.