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
15 Hrs
58 Min
54 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

Creaci贸n de clases y constructores En TypeScript

10/26
Resources

Object-oriented programming is one of the most powerful paradigms in software development, and TypeScript provides robust tools to implement it correctly. Classes are fundamental to this approach, providing a clear structure for code inheritance and object creation. Let's explore how to implement classes in TypeScript following best practices.

What are classes in TypeScript and how do they differ from interfaces?

Although interfaces and classes may appear similar at first glance, they have different implementations and purposes. Interfaces, which we have already explored above, define contracts that classes must fulfill. Classes, on the other hand, provide a more square, defined structure for inheriting code and sharing it with other elements of your project.

The basic syntax for creating a class in TypeScript is fairly straightforward:

class Person { name: string; age: number; developer: boolean;
 constructor(name: string, age: number, developer: boolean) { this.name = name; this.age = age; this.developer = developer; }
 greet(): string { return `Hello, my name is ${this.name} and I am ${this.age} years old`; } }}

In this example, we have created a Person class with three properties: name, age and developer. We have also defined a constructor and a greet() method.

What is the constructor and why is it important?

The constructor is a special method that is executed when an instance of the class is created. Its main function is to initialize the properties of the class with the provided values. In our example, the constructor receives three parameters and assigns them to the corresponding properties of the class.

It is important to note the use of this to refer to the properties of the class, distinguishing them from the constructor parameters. By convention, they are usually named the same, which makes it easier to identify which parameters correspond to which properties.

How to implement and use a class in TypeScript?

Once the class is defined, we can create instances of it and use its methods:

let person = new Person("John", 30, true);console.log(person.greet()); // Print: "Hello, my name is John and I'm 30 years old."

Here, we have created a new instance of the Person class with the values "John", 30 and true. Then, we call the greet() method of this instance to get a custom message.

What are the best practices for organizing classes in a project?

A fundamental practice that is often overlooked is to keep each class in its own file. This follows the "one file, one class" principle and makes your code more maintainable and scalable.

To implement this, we need to:

  1. Export the class from its file:
// class.tsexport class Person { name: string; age: number; developer: boolean;
 constructor(name: string, age: number, developer: boolean) { this.name = name; this.age = age; this.developer = developer; }
 greet(): string { return `Hello, my name is ${this.name} and I am ${this.age} years old`; } }}
  1. Import the class into the file where we want to use it:
// implementation.tsimport { Person } from './class';
let person = new Person("John", 30, true);console.log(person.greet());

This separation allows the class to be agnostic with respect to how it is used, and facilitates its reuse in different parts of your project.

Why is modularization important in class development?

Modularization is key to maintaining clean and organized code. By separating the definition of a class from its implementation, we are following the principle of single responsibility: each file has only one reason to change.

In addition, this practice facilitates:

  • Code reuse
  • Unit testing
  • Team collaboration
  • Long-term maintainability

When you define a class in its own file and export it, you can import it in as many places as you need, implementing it in different ways according to the specific requirements of each part of your application.

Classes in TypeScript offer a powerful and structured way to implement object-oriented programming. By following best practices for organization and modularization, you can create cleaner, more maintainable and reusable code. Have you implemented classes in your TypeScript projects? Share your experiences and questions in the comments.

Contributions 2

Questions 0

Sort by:

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

Las clases en TypeScript son plantillas que permiten crear objetos con propiedades y m茅todos. Un constructor es un m茅todo especial que se ejecuta al instanciar la clase. Se utiliza para inicializar los atributos del objeto. Cuando defines una clase, puedes agregar un constructor utilizando la palabra reservada `constructor`. Este constructor puede recibir par谩metros que se asignan a las propiedades del objeto usando `this`. Por ejemplo: ```typescript class Persona { nombre: string; edad: number; constructor(nombre: string, edad: number) { this.nombre = nombre; this.edad = edad; } saludar() { return `Hola, mi nombre es ${this.nombre} y tengo ${this.edad} a帽os.`; } } const juan = new Persona("Juan", 30); console.log(juan.saludar()); // Hola, mi nombre es Juan y tengo 30 a帽os. ``` Esto permite que cada objeto creado con la clase tenga valores espec铆ficos. Adem谩s, es recomendable mantener la implementaci贸n de la clase en un archivo separado, siguiendo las mejores pr谩cticas para la organizaci贸n del c贸digo, tal como se mencion贸 en el transcript de la clase.
Las ***clases*** son plantillas para crear objetos, y los objetos son instancias de esas clases. Una ***Clase*** est谩 compuesta por un Constructor, Propiedades y M茅todos. Con las clases puedes implementar ***Herencia*** que es una de las caracter铆sticas de la Programaci贸n Orientada a Objetos ***POO***. La ***POO*** es uno de los *paradigmas* m谩s poderosos en el desarrollo de software