Fundamentos de TypeScript
¿Qué es TypeScript y por qué usarlo?
Instalación de Node.js y TypeScript CLI, configuración de tsconfig.json
Tipos primitivos: string, number, boolean, null, undefined de Typescript
Tipos especiales: any, unknown, never, void de TypeScript
Arrays, Tuplas, Enums en TypeScript
Funciones e Interfaces
Declaración de funciones, tipado de parámetros y valores de retorno
Parámetros opcionales, valores por defecto y sobrecarga de funciones
Creación y uso de interfaces de TypeScript
Propiedades opcionales, readonly, extensión de interfaces en TypeScript
Clases y Programación Orientada a Objetos
Creación de clases y constructores En TypeScript
Modificadores de acceso (public, private, protected) en Typescript
Uso de extends, sobreescritura de métodos en TypeScript
Introducción a Genéricos en Typescript
Restricciones con extends, genéricos en interfaces
Módulos y Proyectos
Importación y exportación de módulos en TypeScript
Agregando mi archivo de Typescript a un sitio web
Configuración de un proyecto Web con TypeScript
Selección de elementos, eventos, tipado en querySelector en TypeScript
Crear un proyecto de React.js con Typescript
Crea un proyecto con Angular y Typescript
Crea una API con Typescript y Express.js
Conceptos Avanzados
Introducción a types en TypeScript
Implementación de Decoradores de TypeScript
Async/await en Typescript
Pruebas unitarias con Jest y TypeScript
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
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.
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:
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; } }}
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.
Access modifiers are not just a syntactic formality, they serve crucial functions in software design:
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.
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.
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.
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
Want to see more contributions, questions and answers from the community?