Alan Quispe
Definitivamente amo TypeScript
Miguel Peláez
Es demasiado bien estructurado. Muy poderoso
Moisés Manuel Morín Hevia
Es Js con poderes xD
Alan Quispe
Definitivamente amo TypeScript
Miguel Peláez
Es demasiado bien estructurado. Muy poderoso
Moisés Manuel Morín Hevia
Es Js con poderes xD
Hector Rubi Garcia
Victoria Ramirez Charles
Jaime David Burbano Montoya
Andres Felipe Pinchao Ramirez
Moisés Manuel Morín Hevia
Excelentes notas ! muchas gracias.
Avilio Fernando Amador Soto
Gracias por el aporte. nada más me fijé que te hizo falta agregar el tipo de PhotoOrientation en la const picture.
Luis Abdel Rangel Castro
Jhon Mario Lotero Salazar
Cuando es mejor usar interfaces y cuando clases?
Edwin Alberto López Almira
Las interfaces estan más orientadas en comportamientos, es decir, en métodos que pueden estar en más de una familia. Por ejemplo: Puedes tener las familias de clases Medicinas y Comida, en principio tienen atributos muy distintos, pero comparten el comportamiento de "ingerirse".
Las clases definen atributos y comportamientos que pueden heredarse a clases hijas, pero no a clases que esten en otras familias; las interfaces pueden heredarse o usarse independientemente de la familia de clases en la que se llame.
Espero que te pueda ayuda, suerte en tu aprendizaje :D
José Heriberto López Ruiz
Una interfaz no define lo que hacen los métodos, solamente define la estructura que deben tener las clases que implementan dicha interfaz (es decir, define qué funciones debes de implementar obligatoriamente, pero no te especifica lo que deban hacer exactamente). En cambio, si heredas una clase, entonces estás heredando también los comportamientos definidos en esas funciones. Es decir, si la clase que heredaste tiene algunas funciones con código definido, entonces estarás heredando también esos comportamientos con código definido. Una interfaz te obliga a que definas esas funciones, pero el heredar una clase, no te obliga a que definas esos comportamientos, porque ya están heredados.
David Gómez
Andrés Felipe Eslava Zuluaga
Pablo Cabrera
muy buen resumen bro, gracias :D
Jose Daniel Barría Reyes
Tipea las clases User, Album, Picture. La única diferencia con javascript es que usa tipos en los args.
Moisés Manuel Morín Hevia
Buena observación.
Elber Liebermen
Tengo la siguiente duda. ¿Cuál es la diferencia que hay de declarar el objeto de la forma 1 a la forma 2?
1. const album = new Album (1,'Personal Pictures');
2. const album: Album = new Album (1,'Personal Pictures');
Puedo omitir el tipo de dato ya que especifico que es un objeto instanciado de la clase Albúm?
Juan Antonio García Sánchez
Me encanta lo parecido que tiene a Java 😍
Moisés Manuel Morín Hevia
Demasiado pero más sencillo xD
Ciro Alejandro Sira Mogollon
tengo una pregunta referente al ejemplo del álbum. el profesor definió el tipo de type de las variables antes de la funcion. Es necesario definir el type en los parámetro () ya estando definido antes. no se debería haberse guardado la referencia antes.
Miguel Angel Reyes Moreno
Jimmy Buriticá Londoño
Me ha gustado la forma en que se dan las clases, primero teoría y luego un ejemplo sencillo.
Miguel Angel
Hernán Alexis Moreno Castro
"Pero veámoslo de una manera práctica"... Me encanta aprender practicando
Moisés Manuel Morín Hevia
Pracmaticidad es lo tuyo !
Moisés Manuel Morín Hevia
Clases Diferentes entidades que guardan relación en común. Abstracción de un conjunto de objetos. Propiedades & funciones. Para crear objetos con estas clases constructor(función), valores que recibo como parámetro y asignarlos a las propiedades this.propiedades.
Juan Jiménez
Axel Enrique Galeed Gutierrez
Consulta. Cuando el profesor coloca:
const album: Album = new Album(1, 'Personal Pictures'); const picture: Picture = new Picture(2, 'Platzi session', PhotoOrientation.Square);
El tipo de dato Album y Picture ¿de dónde salen?, ya que no vi que haya definido una interfaz.
A la manera que yo lo interpreto es que a las clases, en TypeScript, también se las pueden usar como interfaces. Corríjanme si estoy mal.
Gracias. :D
Juan Pablo Bedoya Rodriguez
code
Para la clase de Album inicializa el arreglo pictures en el constructor . Me surgió la pregunta de: ¿Cuál seria la diferencia entre inicializar una variable en el constructor...
class Album { pictures: Picture[] constructor() { this.pictures = [] } }
... o inicializarla en la definición de la variable?
class Album { pictures: Picture[] = [] constructor() { } }
¿Sera alguna cuestión de rendimiento, funcionalidad o es por buena práctica?
A mi entender es un tema de gusto, porque por ejemplo: imagina que tienes dos constructores, seria mas efectivo inicializar la propiedad en la declaración en vez de hacerlo en ambos constructores.
class Album { id: number; title: string; pictures: Picture[] = []; constructor (title:string){ this.title = title; } constructor (id: number){ this.id = id; } }
Niguna. No hay diferencias. Hacen lo mismo al igual cuando estas creando variables normales.
let ejemplo: number; number = 2;
es lo mismo que
let ejemplo:number = 2;
MY NOTES FOR CLASES
Definiendo Clases y Constructores
A partir de ECMAScript 2015 es posible construir clases y hacer uso del paradigma de la Programación Orientada a Objetos en Javascript
Typescript permite aplicar estas técnicas sin tener que es esperar por otra versión.
export{} enum PhotoOrientation { Landscape, Portrait, Square, Panorama } class Picture { //Propiedades id:number; title:string; orientation:PhotoOrientation; constructor(id:number,title:string,orientation:PhotoOrientation){ this.id = id; this.title = title; this.orientation = orientation; } //Comportamiento de nuestra clase que estara definido por funciones toString(){ return `[id ${this.id}, title: ${this.title}, orientation: ${this.orientation}]`; } } class Album{ id:number; title:string; pictures: Picture[]; //Usamos el constructor el cual nos permitira crear objetos de esta clase constructor(id:number, title:string){ this.id = id; this.title = title; this.pictures = []; } addPicture(picture:Picture){ this.pictures.push(picture); } } //Creamos un nuevo a partir de la instancia de la clase const album:Album = new Album(1, 'personal pictures'); const picture: Picture = new Picture(1, 'Platzi session', PhotoOrientation) album.addPicture(picture); console.log(album);
export {}; console.clear(); enum PhotoOrientation { Landscape = 'Landscape', Portrait = 'Portrait', Square = 'Square', Panorama = 'Panorama', } // interface Entity { // id: number; // title: string; // } // class Entity { // id: number; // title: string; // } class Picture { id: number; title: string; orientation: PhotoOrientation; constructor(id: number, title: string, orientation: PhotoOrientation) { this.id = id; this.title = title; this.orientation = orientation; } // Comportamiento toString() { return `[id: ${this.id}, title: ${this.title}, orientation: ${this.orientation}]`; } } class Album { id: number; title: string; pictures: Picture[] = []; constructor(id: number, title: string) { this.id = id; this.title = title; // this.pictures = []; } addPicture(picture: Picture) { this.pictures.push(picture); } } const picture: Picture = new Picture(100, 'cool', PhotoOrientation.Square); const picture1 = new Picture(201, 'korn', PhotoOrientation.Square); const album: Album = new Album(534, 'Family'); console.log(picture); console.log(picture1); album.addPicture(picture); album.addPicture(picture1); console.log('album',album);
El ejemplo del profesor un llevado un poco más allá:
enum Orientation { Landscape, Portrait, Square, Panoramic } class Album { readonly id: number; title : string; pictures : Picture[]; constructor(id: number, title: string) { this.id = id; this.title = title this.pictures = [] } toString () : string{ return `Id: ${this.id}\nTitle: ${this.title}`; } addPicture (picture : Picture) { this.pictures.push(picture); } } class Picture extends Album { albumId : number; orientation : Orientation; constructor (id: number, title: string, albumId : number, orientation : Orientation) { super(id, title); this.albumId = albumId; this.orientation = orientation; } toString () : string{ return `Id: ${this.id}\nTitle: ${this.title}\nAlbum: ${this.albumId}\nOrientation: ${this.orientation}`; } } const birthDay = new Album (3, "Birthday"); const newPic = new Picture (4, "Cake", 3, Orientation.Square); birthDay.addPicture(newPic); console.log(birthDay.toString()); console.log(""); console.log(birthDay.pictures[0].toString());
export {} enum PhotoOrientation { Landscape, Portrait, Square, Panorama, }; class Picture { // properties id: number; title: string; orientation: PhotoOrientation; //constructor constructor( id: number, title: string, orientation: PhotoOrientation ) { this.id = id; this.title = title; this.orientation = orientation; } //Performance toString() { return `[id: ${this.id}, title: ${this.title}, orientation: ${this.orientation}]` } } class Album { id: string; title: string; pictures: Picture[]; constructor( id: string, title: string ) { this.id = id; this.title = title; this.pictures = []; } addPicture(picture: Picture) { this.pictures.push(picture); } } let album: Album = new Album('stories-1', 'Photos of mine'); const newPic: Picture = new Picture(2, 'my new pic!', PhotoOrientation.Panorama); const new2Pic: Picture = new Picture(3, 'my 2nd new pic!', PhotoOrientation.Portrait); const new3Pic: Picture = new Picture(4, 'my 3rd new pic!', PhotoOrientation.Portrait); album.addPicture(newPic); album.addPicture(new2Pic); album.addPicture(new3Pic); console.log('album -> ', album);
No sé si han sido curiosos, pero nos estamos ahorrando mucho código en JS con el poder de TS, solamente comparen: Código en TS:
export {} enum PhotoOrientation{ Landscape, Portrait, Square, Panorama } class Picture { //* Propiedades id: number title: string orientation: PhotoOrientation //*Atributos que se consideran necesarios para construir objetos constructor(id: number, title: string, orientation: PhotoOrientation) { this.id = id this.title = title this.orientation = orientation } //*Comportamiento toString() { return ` [ id: ${this.id}, title: ${this.title}, orientation: ${this.orientation} ] ` } } class Album { id: number title: string pictures: Picture[] constructor(id: number, title: string) { this.id = id this.title = title this.pictures = [] //*Inicializamos el array vacío } addPicture(picture: Picture) { this.pictures.push(picture) } } const album: Album = new Album(1, 'Personal Pictures') const picture: Picture = new Picture(1, 'Selfie', PhotoOrientation.Square) album.addPicture(picture) //console.table(album) //console.table(picture) //console.table({picture}) console.log(album) //* Imprime el objeto console.table({album}) //* Como manejamos un objeto, podemos usar console.table console.table(album.pictures) //* Como tenemos un array dentro del objeto, también podemos usar console.table
Código en JS:
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PhotoOrientation; (function (PhotoOrientation) { PhotoOrientation[PhotoOrientation["Landscape"] = 0] = "Landscape"; PhotoOrientation[PhotoOrientation["Portrait"] = 1] = "Portrait"; PhotoOrientation[PhotoOrientation["Square"] = 2] = "Square"; PhotoOrientation[PhotoOrientation["Panorama"] = 3] = "Panorama"; })(PhotoOrientation || (PhotoOrientation = {})); class Picture { //*Atributos que se consideran necesarios para construir objetos constructor(id, title, orientation) { this.id = id; this.title = title; this.orientation = orientation; } //*Comportamiento toString() { return ` [ id: ${this.id}, title: ${this.title}, orientation: ${this.orientation} ] `; } } class Album { constructor(id, title) { this.id = id; this.title = title; this.pictures = []; //*Inicializamos el array vacío } addPicture(picture) { this.pictures.push(picture); } } const album = new Album(1, 'Personal Pictures'); const picture = new Picture(1, 'Selfie', PhotoOrientation.Square); album.addPicture(picture); //console.table(album) //console.table(picture) //console.table({picture}) console.log(album); //* Imprime el objeto console.table({ album }); //* Como manejamos un objeto, podemos usar console.table console.table(album.pictures); //* Como tenemos un array dentro del objeto, también podemos usar console.table
Agregó un aporte de como utilizar el ejemplo de clases a partir de un caso diferente (Pedidos de Comida)
// CLASSES /* Las clases y en general la POO pueden ser usadas a partir de ES5, así como todos sus conceptos. */ /** * A partir de un ejemplo con una aplicacion de pedidos de comida * existen varias entidades: * Usuarios: Quies hacen los pedidos * order_status: Enum con estado de los pedidos * Pedidos: La conjuncion de los pedidos que se van a ordenar * Comida: La comida que se esta pidiendo * * Usuario ---> Comida --> Orden --> Status */ // tipo de dato enum para almacenar es estado de las ordenes enum OrderStatus { not_attended = 0, attended = 1, ready = 2, done = 3 } // CLASE DE FOOD PARA CREAR NUEVOS ALIMENTOS class Food { id_food: number; food_name: string; price: number; description: string; constructor( id_food: number, food_name: string, price: number, description: string ) { this.id_food = id_food; this.food_name = food_name; this.price = price; this.description = description; } } // CLASE PARA GUARDAR LAS ORDENES DE LOS USUARIOS class UserOrders { id_order: number; id_user: User; order_status: OrderStatus; food_order: Array<[Food]> = []; constructor(id_order: number, id_user: User, order_status: OrderStatus) { this.id_order = id_order; this.id_user = id_user; this.order_status = order_status; } addNewFoodToOrder(food: Food) { this.food_order.push([food]); } } //CLASE DE USER PARA MANEJAR A LOS USUARIOS class User { id_user: number; user_name: string; isPro: boolean; constructor(id_user: number, user_name: string, isPro: boolean) { this.id_user = id_user; this.user_name = user_name; this.isPro = isPro; } getMyUser() { console.log(this.id_user, this.user_name, this.isPro); } } // CREAMOS NUESTRO USUARIO QUE CREARA LOS PEDIDOS const my_new_user: User = new User(1, 'Mike', true); console.table(my_new_user); // CREAMOS LOS PLATILLOS EXISTENTES const platillo_1: Food = new Food(1, 'Tortas', 20.00, 'Tortas de un Ingrediente'); console.table(platillo_1); const platillo_2: Food = new Food(2, 'Enchiladas', 10.00, 'Orden de 4 enchiladas.'); console.table(platillo_2); // CREAMOS UNA NUEVA ORDEN DE COMIDA const nueva_orden: UserOrders = new UserOrders(1, my_new_user, OrderStatus.not_attended) nueva_orden.addNewFoodToOrder(platillo_1); nueva_orden.addNewFoodToOrder(platillo_2); console.log(nueva_orden.food_order);
export {}; enum PhotoOrientation { Landscape, Portrait, Square, Panorama } class Picture { // Propiedades id: number; title: string; orientation: PhotoOrientation; constructor(id: number, title: string, orientation: PhotoOrientation) { this.id = id; this.title = title; this.orientation = orientation; } // Comportamiento toString() { return `[id: ${this.id}, title: ${this.title}, orientation: ${this.orientation}]`; } } class Album { id: number; title: string; pictures: Picture[]; constructor(id: number, title: string) { this.id = id; this.title = title; this.pictures = []; } addPicture(picture: Picture) { this.pictures.push(picture); } } const album: Album = new Album(1, 'Personal Pictures'); const picture: Picture = new Picture(1, 'Platzi session', PhotoOrientation.Square); album.addPicture(picture); console.log('album', album);