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
6 Hrs
24 Min
58 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

Modificadores de acceso (public, private, protected) en Typescript

11/26
Resources

Object-oriented programming (OOP) is one of the most powerful paradigms in software development, allowing us to create organized and reusable code structures. One of the fundamental concepts of OOP is the control of access to properties and methods, which allows us to establish different levels of visibility for our components. Understanding these access levels is crucial for designing robust and safe classes in any programming language.

What are access modifiers in classes?

Access modifiers are keywords that determine from where the properties and methods of a class can be accessed. These modifiers are fundamental to implement the encapsulation principle, one of the pillars of object-oriented programming.

In most object-oriented programming languages, there are three main access modifiers:

  • Public: Accessible from anywhere in the code.
  • Protected: Accessible only from the class itself and its derived classes.
  • Private: Accessible only from within the class where it is defined.

Let's see how to implement these modifiers in our code:

class Person { // public is accessible from anywhere public name: string;    
 // protected is only accessible within the class and inheriting classes protected age: number;    
 // private is only accessible within the class private developer: boolean;    
 constructor(name: string, age: number, developer: boolean) { this.name = name; this.age = age; this.developer = developer; }    
 public greet(): string { return `Hello, my name is ${this.name}`; }    
 protected getAge(): number { return this.age; }    
 private esDev(): boolean { return this.developer; } }}

How do access modifiers affect visibility?

When we define a class with different access modifiers, we are setting rules about how that class can be interacted with from different parts of our code.

If we create an instance of the Person class in another file:

const person = new Person("John", 30, true);
// We can access public properties and methodsconsole.log(person.name); // "John"console.log(person.greet()); // "Hello, my name is John"
// But we cannot access protected or private elements// console.log(person.age); // Error: Property 'age' is protected// console.log(person.getAge()); // Error: Property 'getAge' is protected// console.log(person.developer); // Error: Property 'developer' is private// console.log(person.enDev()); // Error: Property 'enDev' is private

It is important to note that code editors such as Visual Studio Code help us to identify which elements are accessible through auto-completion. When we type person. only the available public properties and methods will appear.

Why are access modifiers important?

Access modifiers are not just a syntactic formality, they serve crucial functions in software design:

Encapsulation and security.

The proper use of access modifiers allows us to hide the internal implementation of our classes, exposing only what is necessary for their use. This is fundamental to create stable and secure APIs.

For example, in a class that handles database connections:

class DatabaseManager { private connection: any;    
 private connectToDatabase() { // Sensible connection logic this.connection = /* connection code */; }    
 public getData(query: string) { if (!this.connection) { this.connectToDatabase(); } // Return data }}

In this case, we make the database connection method private to protect sensitive information, while we publicly expose only the method to get data.

Code maintenance and evolution

By limiting access to certain components, we can modify the internal implementation without affecting the code used by our class, as long as we keep the same public interface.

Clarity of intent

Access modifiers clearly communicate to other developers (and our future selves) which parts of the class are intended to be used externally and which are internal implementation details.

How to choose the right access modifier?

The choice of access modifier depends on the purpose of each property or method:

  • Public: use this modifier for elements that are part of the public API of your class, which need to be accessible from anywhere in the code.

  • Protected: It is ideal for elements that must be accessible from the current class and its subclasses, but not from the outside. Useful when implementing inheritance.

  • Private: Reserve this modifier for internal implementation details that should not be accessible or visible from outside the class.

A good practice is to start with the most restrictive level possible (private) and only increase visibility when necessary.

Access modifiers are powerful tools that help us create more robust, maintainable and secure code. Mastering their use is essential for any developer working with object-oriented programming. We invite you to experiment with the different access levels in your own classes to better understand how they can improve the structure of your code.

Have you used access modifiers in your projects? What strategies do you follow to decide the visibility of your properties and methods? Share your experience in the comments.

Contributions 2

Questions 0

Sort by:

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

Los modificadores de acceso en TypeScript son esenciales para controlar la visibilidad de propiedades y métodos en las clases. Hay tres tipos principales: 1. **public**: Este es el modificador por defecto. Las propiedades y métodos marcados como públicos pueden ser accedidos desde cualquier parte del código, tanto dentro de la clase como fuera de ella. Ejemplo: ```typescript class Persona { public nombre: string; constructor(nombre: string) { this.nombre = nombre; } } ``` 2. **private**: Las propiedades y métodos privados solo pueden ser accedidos dentro de la misma clase. Esto es útil para encapsular la lógica interna de la clase y proteger datos sensibles de accesos externos. Ejemplo: ```typescript class Persona { private edad: number; constructor(edad: number) { this.edad = edad; } } ``` 3. **protected**: Similar a private, pero las propiedades y métodos protegidos pueden ser accedidos dentro de la misma clase y en clases que heredan de ella. Esto es útil en situaciones de herencia donde se desea permitir que las subclases accedan a ciertos datos. Ejemplo: ```typescript class Persona { protected edad: number; constructor(edad: number) { this.edad = edad; } } class Estudiante extends Persona { constructor(edad: number) { super(edad); console.log(this.edad); // Acceso permitido } } ``` Estos modificadores ayudan a mantener un código ordenado y seguro, garantizando que solo las partes adecuadas del código tengan acceso a los datos críticos. Utiliza modificadores de acceso de manera consciente para mejorar la robustez de tus aplicaciones en TypeScript.
Así como la ***Herencia*** es una característica de la ***POO***, el ***Encapsulamiento*** también y este se refiere a la seguridad y/o visibilidad que tendrán las otras Clases a tus Constructores, Propiedades y Métodos. En la mayoría de los lenguajes de ***POO***, existen tres modificadores de acceso principales: • ***Public***: Accesible desde cualquier parte del código. • ***Protected***: Accesible solo desde la clase misma y sus clases derivadas. • ***Private***: Accesible únicamente desde dentro de la clase donde se define.