CursosEmpresasBlogLiveConfPrecios

Setters

Clase 8 de 25 • Curso de TypeScript: Programación Orientada a Objetos y Asincronismo

Clase anteriorSiguiente clase

Contenido del curso

Introducción
  • 1
    ¿Ya tomaste el Curso de TypeScript: Tipos Avanzados y Funciones?

    ¿Ya tomaste el Curso de TypeScript: Tipos Avanzados y Funciones?

    05:16
Fundamentos de POO
  • 2
    Class

    Class

    12:19
  • 3
    Métodos

    Métodos

    08:44
  • 4
    Acceso público

    Acceso público

    05:16
  • 5
    Acceso privado

    Acceso privado

    10:20
  • 6
    Constructor

    Constructor

    08:00
  • 7
    Getters

    Getters

    11:48
  • 8
    Setters

    Setters

    07:55
POO Avanzada
  • 9
    Herencia

    Herencia

    10:18
  • 10
    Acceso protegido

    Acceso protegido

    08:02
  • 11
    Static

    Static

    12:01
  • 12
    Interfaces

    Interfaces

    13:45
  • 13
    Clases abstractas

    Clases abstractas

    06:14
  • 14
    Singleton: constructor privado

    Singleton: constructor privado

    10:36
Asincronismo y consumo de APIs
  • 15
    Promesas

    Promesas

    14:13
  • 16
    Tipando respuestas HTTP

    Tipando respuestas HTTP

    11:38
  • 17
    Proyecto: migración de funciones a clases

    Proyecto: migración de funciones a clases

    10:05
  • 18
    Consumiendo ProductMemoryService

    Consumiendo ProductMemoryService

    06:30
  • 19
    ProductHttpService

    ProductHttpService

    15:33
  • 20
    Consumiendo ProductHttpService

    Consumiendo ProductHttpService

    09:22
Genéricos
  • 21
    Generics

    Generics

    10:22
  • 22
    Generics en clases

    Generics en clases

    12:08
  • 23
    Generics en métodos

    Generics en métodos

    15:11
  • 24
    Decoradores

    Decoradores

    15:05
Próximos pasos
  • 25
    ¿Quieres más cursos de TypeScript?

    ¿Quieres más cursos de TypeScript?

    01:20
    Axel Enrique Galeed Gutierrez

    Axel Enrique Galeed Gutierrez

    student•
    hace 4 años

    Les comparto mis apuntes. :D

    Set

    Es parecido a un get, solo que este no retorna nada, es un método void, pero no hace falta colocarle lo que retorna, ya que va a dar error.

    A set lo podemos usar para tener reglas de modificación para nuestros parámetros.

    Sintaxis

    class ClassName { constructor () { statements } set methodName () { statements } }
      Ronaldo Delgado

      Ronaldo Delgado

      student•
      hace 2 años

      genial

    Katerin Calderón

    Katerin Calderón

    student•
    hace 3 años

    There are some principles to improve yor code and make it cleaner. One thing you can do better is to avoid the use of Else, so a simple solution for a code that requires an else is to validate first the scenario that throw the error and then assign the value, in the example of Nicolas it would stay like this:

    set month(newValue: number) { if(newValue < 1 || newValue > 12 ){ throw new Error ("The month needs to be a number between 1 and 12") } this._month = newValue; }
      carlos pino

      carlos pino

      student•
      hace 2 años

      that's interesting 🤔

    Migdualy Alejandra Gonzalez Martinez

    Migdualy Alejandra Gonzalez Martinez

    student•
    hace 4 años

    el get y set dan interacción como si fueran una propiedad

      Reinaldo Mendoza

      Reinaldo Mendoza

      student•
      hace 3 años

      pero nos hace modificar la propiedad para que no choquen, me parece mejor el método "normal" gatAlgo(){...}

    Jordy Mairena Montoya

    Jordy Mairena Montoya

    student•
    hace 4 años

    Getters and setters

    export type formatDate = 'days' | 'months' | 'years'; class MyDate { private _year: number; private _month: number; private _day: number; private _leapYear: boolean = false; // by deafault the year is not leap year private _months: { [key: number]: string; } = { // dictionari months of the year 1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December' }; private _month31: number[] = [1, 3, 5, 7, 8, 10, 12]; // list of months that have 31 days constructor(year: number, month: number, day: number) { this._year = this._validYear(year); this._validLeapYear() this._month = this._validMonth(month); this._day = this._validDay(day); } printFormat(format: string = 'dd / nm / yy'): string { if (this._validError() == null) { // if validError returns null then there are no errors let day: string = this._addPadding(this._day); let month: string = this._addPadding(this._month); format = format.replace('yy', this._year.toString()); format = format.replace('dd', day); format = format.replace('mm', month); format = format.replace('nm', this._months[this._month]); return format; } else { return this._validError()!; // notation ! tells typescript that the programmer is in control } } // override toString(): string { return this.printFormat(); } get day(): number { return this._day; } set day(num: number) { this._day = this._validDay(num); } get month(): number { return this._month; } set month(num: number) { this._month = this._validMonth(num); this._day = this._validDay(this._day); // this line verifies the assigned values setters } get monthName(): string { return this._months[this._month]; } get year(): number { return this._year; } set year(num: number) { this._year = this._validYear(num); } get leapYear(): boolean { return this._leapYear; } private _validError(): string | null { // if any attribute has the value of zero then it is out of range and there is an error let error: string = '#outRange!'; // out of tange error indicator if (this._year == 0) { return `${error} year`; // error message } if (this._month == 0) { return `${error} month`; // error message } if (this._day == 0) { return `${error} day`; // error message } return null; // whithout errors } private _addPadding(num: number): string { if (num < 10) { return `0${num}`; } return num.toString(); } private _validYear(year: number): number { // if the year is greater than zero it is valid if(year > 0) { return year; } else { return 0; } } private _validDay(day: number): number { // validate the day if (day > 0) { if (this._month === 2) { // if the month is february let evaluateDay: number = 28; if (this._leapYear) { // if leap year evaluateDay++; } if (day <= evaluateDay) { return day; } else { return 0; } } else { // if it is any month except february let evaluateDay: number = 30; if (this._month31.includes(this._month)) { // if the month has 31 days evaluateDay++; } if (day <= evaluateDay) { return day; } else { return 0; } } } else { return 0 } } private _validMonth(month: number): number { // Validated that the month is between 1 and 12 if (month > 0 && month < 13) { return month; } else { return 0; } } private _validLeapYear(): void { /** * @ Check if the year is a leap year */ let result: number; result = (this._year / 4) % 2; // formula if ((n/4) % 2 == 0) if(result == 0) { this._leapYear = true; } } add(amount: number, format: formatDate): void { if (this._validError() == null) { if (format == 'days') { for (let i = 0; i < amount; i++) { this._day += 1; if (this._validDay(this._day) == 0) { // Validated the day based on the month and year /* if _validDay returns 0 the valid days for the current month were exceeded then the month is increased and day is restarted */ this._month++; if (this._month == 13) { this._year++; this._month = 1; } this._day = 1; } } } else if (format == 'months') { for (let i = 0; i < amount; i++) { this._month++; if (this._month > 12) { this._year++; this._month = 1; } } } else if (format == 'years') { if (amount > 0) { this._year += amount; } } } } } const myDate = new MyDate(2000, 2, 29); console.log(myDate.printFormat('dd of nm of yy')); myDate.add(3, 'days'); console.log(myDate.printFormat()); myDate.add(40, 'months'); console.log(myDate.printFormat('mm-dd-yy')); console.log(myDate.toString()); console.log(myDate.day); console.log(myDate.month); console.log(myDate.monthName); console.log(myDate.year); myDate.day = 31; myDate.year = 2000; myDate.month = 2; console.log(myDate.day); console.log(myDate.toString());
    Andrés Muñoz

    Andrés Muñoz

    student•
    hace 3 años

    ¿Por qué el throw new Error no lanzo un error en la consola ?

      Luis Enrique Mena Colín

      Luis Enrique Mena Colín

      student•
      hace 3 años

      Sí sale el error. Yo cambié la condición de la siguiente manera:

      set month(newValue: number) { if(newValue < 1 || newValue > 12) throw new Error('Invalid month') this._month = newValue; }
      Vladimir Farrera Vera

      Vladimir Farrera Vera

      student•
      hace 2 años

      quita el new Error

      public set month(newValue : number) { if (newValue >= 1 && newValue <= 12) { this._month = newValue }else{ throw ("month out of range"); } }
    Alejandro Chavez

    Alejandro Chavez

    student•
    hace 2 años

    Ya que estamos en TS, podríamos también crear un tipo para month, de manera que solo puedan asigarse valores predefinidos en el tipo ¿no?

    Iván Darío Sánchez Jiménez

    Iván Darío Sánchez Jiménez

    student•
    hace 3 años

    Les comparto mi código implementando tratamiento de errores.

    export class MyDate { constructor( public year: number = 1984, public _month: number = 6, private _day: number = 26) {} printFormat(): string { const day = this.addPadding(this._day); const month = this.addPadding(this._month); return `${this.year}/${month}/${day}`; } private addPadding(value: number) { if (value < 10) { return `0${value}`; } return `${value}`; } public add(amount: number, type: 'days' | 'months' | 'years') { if (type === 'days') { this._day += amount; } if (type === 'months') { this._month += amount; } if (type === 'years') { this.year += amount; } } get day() { return this._day; } get isLeapYear(){ if(this.year % 400 === 0) return true if(this.year % 100 === 0) return false return this.year % 4 === 0 } get month(){ return this._month } set month(value: number){ try{ if(value >= 1 && value <= 12){ this._month = value } else{ throw new Error('month out of range') } } catch(e){ const error = (e as Error).message; console.log(error) } } } const newDate = new MyDate(2004, 3, 9); console.log(newDate.month) const newDate2 = new MyDate(2004, 3, 9); newDate2.month = 11 console.log('(11)=>',newDate2.month) const newDate3 = new MyDate(2004, 3, 9); newDate3.month = 25 console.log('(error',newDate3.month) console.log('With error handling')
    Walter Omar Barrios Vazquez

    Walter Omar Barrios Vazquez

    student•
    hace 3 años

    El tipo de retorno del get debe ser asignable con el tipo de entrada para el set, es decir:

    get month(): number {} set month(value: number) {}

    No podría tener un get de la siguiente forma:

    get month(): string { return this.addPadding(this._month) }
    Eminson Mendoza

    Eminson Mendoza

    student•
    hace 10 meses

    Los setters en TypeScript son métodos especiales utilizados para establecer el valor de una propiedad de una clase. Permiten validar o transformar los datos antes de asignarlos. Aquí tienes un ejemplo:

    class Persona { private _edad: number; set edad(valor: number) { if (valor < 0) { console.error("La edad no puede ser negativa."); } else { this._edad = valor; } } get edad(): number { return this._edad; } } const persona = new Persona(); persona.edad = 30; // Establece la edad console.log(persona.edad); // Muestra 30 persona.edad = -5; // Lanza un error

    Esto ilustra cómo los setters pueden ser útiles para controlar la asignación de propiedades.

    Brahyan Antonio Martinez Madera

    Brahyan Antonio Martinez Madera

    student•
    hace 3 años

    Algo que me parece interesante es que los setters no se ejecutan como una funcion sino como una igualdad directamente

    Juan Manuel Luna Blanco

    Juan Manuel Luna Blanco

    student•
    hace 3 años

    rango de meses no era entre 0 y 11??, entonces porque usaste entre 1 y 12?

      Jhonatan Andres Mejia Ramirez

      Jhonatan Andres Mejia Ramirez

      student•
      hace 3 años

      El explico hace algunas clases que los meses eran de 0 a 11 en el Date de js pero como esta es nuestra propia clase MyDate ibamos a manejarla de 1 a 12.

    Ronaldo Delgado

    Ronaldo Delgado

    student•
    hace 2 años

    Excelente video ahora me queda claro los setters y los getters

    Samuel Miranda Martínez

    Samuel Miranda Martínez

    student•
    hace 3 años

    Estas reglas también funcionan para los métodos internos, como el add 🤯🤯🤯.

    public add(amount: number, type: 'days' | 'months' | 'years') { if (type === 'days') { this.day += amount; } if (type === 'months') { this.month += amount; } if (type === 'years') { this.year += amount; } }
    Miguel Angel Reyes Moreno

    Miguel Angel Reyes Moreno

    student•
    hace 4 años

    Setters

    Los setters DEBEN ser void.

    set month(newMonth: number) { if (newMonth < 1 || newMonth > 12) { throw new Error('Invalid month'); } this._month = newMonth; }

    const anotherDate = new MyDate(2024, 1, 1); anotherDate.month = 5; //anotherDate.month = 50; //! Error

Escuelas

  • Desarrollo Web
    • Fundamentos del Desarrollo Web Profesional
    • Diseño y Desarrollo Frontend
    • Desarrollo Frontend con JavaScript
    • Desarrollo Frontend con Vue.js
    • Desarrollo Frontend con Angular
    • Desarrollo Frontend con React.js
    • Desarrollo Backend con Node.js
    • Desarrollo Backend con Python
    • Desarrollo Backend con Java
    • Desarrollo Backend con PHP
    • Desarrollo Backend con Ruby
    • Bases de Datos para Web
    • Seguridad Web & API
    • Testing Automatizado y QA para Web
    • Arquitecturas Web Modernas y Escalabilidad
    • DevOps y Cloud para Desarrolladores Web
  • English Academy
    • Inglés Básico A1
    • Inglés Básico A2
    • Inglés Intermedio B1
    • Inglés Intermedio Alto B2
    • Inglés Avanzado C1
    • Inglés para Propósitos Específicos
    • Inglés de Negocios
  • Marketing Digital
    • Fundamentos de Marketing Digital
    • Marketing de Contenidos y Redacción Persuasiva
    • SEO y Posicionamiento Web
    • Social Media Marketing y Community Management
    • Publicidad Digital y Paid Media
    • Analítica Digital y Optimización (CRO)
    • Estrategia de Marketing y Growth
    • Marketing de Marca y Comunicación Estratégica
    • Marketing para E-commerce
    • Marketing B2B
    • Inteligencia Artificial Aplicada al Marketing
    • Automatización del Marketing
    • Marca Personal y Marketing Freelance
    • Ventas y Experiencia del Cliente
    • Creación de Contenido para Redes Sociales
  • Inteligencia Artificial y Data Science
    • Fundamentos de Data Science y AI
    • Análisis y Visualización de Datos
    • Machine Learning y Deep Learning
    • Data Engineer
    • Inteligencia Artificial para la Productividad
    • Desarrollo de Aplicaciones con IA
    • AI Software Engineer
  • Ciberseguridad
    • Fundamentos de Ciberseguridad
    • Hacking Ético y Pentesting (Red Team)
    • Análisis de Malware e Ingeniería Forense
    • Seguridad Defensiva y Cumplimiento (Blue Team)
    • Ciberseguridad Estratégica
  • Liderazgo y Habilidades Blandas
    • Fundamentos de Habilidades Profesionales
    • Liderazgo y Gestión de Equipos
    • Comunicación Avanzada y Oratoria
    • Negociación y Resolución de Conflictos
    • Inteligencia Emocional y Autogestión
    • Productividad y Herramientas Digitales
    • Gestión de Proyectos y Metodologías Ágiles
    • Desarrollo de Carrera y Marca Personal
    • Diversidad, Inclusión y Entorno Laboral Saludable
    • Filosofía y Estrategia para Líderes
  • Diseño de Producto y UX
    • Fundamentos de Diseño UX/UI
    • Investigación de Usuarios (UX Research)
    • Arquitectura de Información y Usabilidad
    • Diseño de Interfaces y Prototipado (UI Design)
    • Sistemas de Diseño y DesignOps
    • Redacción UX (UX Writing)
    • Creatividad e Innovación en Diseño
    • Diseño Accesible e Inclusivo
    • Diseño Asistido por Inteligencia Artificial
    • Gestión de Producto y Liderazgo en Diseño
    • Diseño de Interacciones Emergentes (VUI/VR)
    • Desarrollo Web para Diseñadores
    • Diseño y Prototipado No-Code
  • Contenido Audiovisual
    • Fundamentos de Producción Audiovisual
    • Producción de Video para Plataformas Digitales
    • Producción de Audio y Podcast
    • Fotografía y Diseño Gráfico para Contenido Digital
    • Motion Graphics y Animación
    • Contenido Interactivo y Realidad Aumentada
    • Estrategia, Marketing y Monetización de Contenidos
  • Desarrollo Móvil
    • Fundamentos de Desarrollo Móvil
    • Desarrollo Nativo Android con Kotlin
    • Desarrollo Nativo iOS con Swift
    • Desarrollo Multiplataforma con React Native
    • Desarrollo Multiplataforma con Flutter
    • Arquitectura y Patrones de Diseño Móvil
    • Integración de APIs y Persistencia Móvil
    • Testing y Despliegue en Móvil
    • Diseño UX/UI para Móviles
  • Diseño Gráfico y Arte Digital
    • Fundamentos del Diseño Gráfico y Digital
    • Diseño de Identidad Visual y Branding
    • Ilustración Digital y Arte Conceptual
    • Diseño Editorial y de Empaques
    • Motion Graphics y Animación 3D
    • Diseño Gráfico Asistido por Inteligencia Artificial
    • Creatividad e Innovación en Diseño
  • Programación
    • Fundamentos de Programación e Ingeniería de Software
    • Herramientas de IA para el trabajo
    • Matemáticas para Programación
    • Programación con Python
    • Programación con JavaScript
    • Programación con TypeScript
    • Programación Orientada a Objetos con Java
    • Desarrollo con C# y .NET
    • Programación con PHP
    • Programación con Go y Rust
    • Programación Móvil con Swift y Kotlin
    • Programación con C y C++
    • Administración Básica de Servidores Linux
  • Negocios
    • Fundamentos de Negocios y Emprendimiento
    • Estrategia y Crecimiento Empresarial
    • Finanzas Personales y Corporativas
    • Inversión en Mercados Financieros
    • Ventas, CRM y Experiencia del Cliente
    • Operaciones, Logística y E-commerce
    • Gestión de Proyectos y Metodologías Ágiles
    • Aspectos Legales y Cumplimiento
    • Habilidades Directivas y Crecimiento Profesional
    • Diversidad e Inclusión en el Entorno Laboral
    • Herramientas Digitales y Automatización para Negocios
  • Blockchain y Web3
    • Fundamentos de Blockchain y Web3
    • Desarrollo de Smart Contracts y dApps
    • Finanzas Descentralizadas (DeFi)
    • NFTs y Economía de Creadores
    • Seguridad Blockchain
    • Ecosistemas Blockchain Alternativos (No-EVM)
    • Producto, Marketing y Legal en Web3
  • Recursos Humanos
    • Fundamentos y Cultura Organizacional en RRHH
    • Atracción y Selección de Talento
    • Cultura y Employee Experience
    • Gestión y Desarrollo de Talento
    • Desarrollo y Evaluación de Liderazgo
    • Diversidad, Equidad e Inclusión
    • AI y Automatización en Recursos Humanos
    • Tecnología y Automatización en RRHH
  • Finanzas e Inversiones
    • Fundamentos de Finanzas Personales y Corporativas
    • Análisis y Valoración Financiera
    • Inversión y Mercados de Capitales
    • Finanzas Descentralizadas (DeFi) y Criptoactivos
    • Finanzas y Estrategia para Startups
    • Inteligencia Artificial Aplicada a Finanzas
    • Domina Excel
    • Financial Analyst
    • Conseguir trabajo en Finanzas e Inversiones
  • Startups
    • Fundamentos y Validación de Ideas
    • Estrategia de Negocio y Product-Market Fit
    • Desarrollo de Producto y Operaciones Lean
    • Finanzas, Legal y Fundraising
    • Marketing, Ventas y Growth para Startups
    • Cultura, Talento y Liderazgo
    • Finanzas y Operaciones en Ecommerce
    • Startups Web3 y Blockchain
    • Startups con Impacto Social
    • Expansión y Ecosistema Startup
  • Cloud Computing y DevOps
    • Fundamentos de Cloud y DevOps
    • Administración de Servidores Linux
    • Contenerización y Orquestación
    • Infraestructura como Código (IaC) y CI/CD
    • Amazon Web Services
    • Microsoft Azure
    • Serverless y Observabilidad
    • Certificaciones Cloud (Preparación)
    • Plataforma Cloud GCP

Platzi y comunidad

  • Platzi Business
  • Live Classes
  • Lanzamientos
  • Executive Program
  • Trabaja con nosotros
  • Podcast

Recursos

  • Manual de Marca

Soporte

  • Preguntas Frecuentes
  • Contáctanos

Legal

  • Términos y Condiciones
  • Privacidad
  • Tyc promociones
Reconocimientos
Reconocimientos
Logo reconocimientoTop 40 Mejores EdTech del mundo · 2024
Logo reconocimientoPrimera Startup Latina admitida en YC · 2014
Logo reconocimientoPrimera Startup EdTech · 2018
Logo reconocimientoCEO Ganador Medalla por la Educación T4 & HP · 2024
Logo reconocimientoCEO Mejor Emprendedor del año · 2024
De LATAM conpara el mundo
YoutubeInstagramLinkedInTikTokFacebookX (Twitter)Threads