Skip to content

Commit

Permalink
add utilty types WIP b00tc4mp#1
Browse files Browse the repository at this point in the history
  • Loading branch information
frankpereiragomez committed Nov 19, 2024
1 parent 03fb734 commit 36202b9
Show file tree
Hide file tree
Showing 7 changed files with 151 additions and 1 deletion.
26 changes: 26 additions & 0 deletions stuff/ts/src/utility-types/Omit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/* Constructs a type by picking all properties from Type and then removing
Keys (string literal or union of string literals). The opposite of Pick.
Construye un tipo excluyendo un subconjunto de propiedades de otro tipo.
Ejemplo en Entorno de Trabajo:
Al exponer datos de usuarios en una API, quieres omitir campos
sensibles como contraseñas.
*/

interface User {
id: number;
name: string;
email: string;
password: string;
}

type PublicUser = Omit<User, "password">;

const publicUser: PublicUser = {
id: 1,
name: "Pantaleon",
email: "[email protected]",
};

console.log("publicUser :>> ", publicUser);
30 changes: 30 additions & 0 deletions stuff/ts/src/utility-types/Partial.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
Partial<Type>
Constructs a type with all properties of Type set to optional. This utility
will return a type that represents all subsets of a given type.
Esto es útil para funciones de actualización donde no todos los campos deben
ser proporcionados.
*/

type Todo = {
text: string;
description: string;
isDone: boolean;
};

const updateTodo = (todo: Todo, filesToUpdate: Partial<Todo>): Todo => {
return { ...todo, ...filesToUpdate };
};

const newTodo: Todo = {
description: "hacer compra en el super",
text: "ir al Consume a por galletas Dinosauirios",
isDone: false,
};

const updatedTodo = updateTodo(newTodo, { isDone: true });

console.log("updatedTodo :>> ", updatedTodo);

//TODO Actualizar el perfil de un usuario
23 changes: 23 additions & 0 deletions stuff/ts/src/utility-types/Pick.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/* Pick<T, K>
Constructs a type by picking the set of properties Keys (string literal or union
of string literals) from Type.
Ejemplo en Entorno de Trabajo:
Cuando necesitas enviar solo cierta información al cliente o mostrar un resumen
de datos.
*/

interface Task {
description: string;
isCompleted: boolean;
difficulty: "easy" | "medium" | "hard";
}

type TaskResume = Pick<Task, "description" | "isCompleted">;

const studyTypescript: TaskResume = {
description: "Study Typescript",
isCompleted: true,
};

console.log("studyTypescript :>> ", studyTypescript);
19 changes: 19 additions & 0 deletions stuff/ts/src/utility-types/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# ¿Qué son los Utility Types en TypeScript?

Los Utility Types en TypeScript son tipos predefinidos que facilitan la manipulación y transformación de tipos existentes. Permiten crear nuevos tipos basados en tipos ya definidos, aplicando modificaciones como hacer todas las propiedades opcionales, requeridas, de solo lectura, etc.

Estos tipos utilitarios son especialmente útiles para:

Evitar repetición de código.
Mejorar la reutilización y consistencia de tipos.
Facilitar el mantenimiento y escalabilidad del código.

Utility Types Esenciales para Principiantes
Para estudiantes que están comenzando con TypeScript, es recomendable enfocarse en los siguientes Utility Types:

- Partial<T>
- Required<T>
- Readonly<T>
- Pick<T, K>
- Omit<T, K>
- Record<K, T>
23 changes: 23 additions & 0 deletions stuff/ts/src/utility-types/Readonly.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/* Constructs a type with all properties of Type set to readonly, meaning the
properties of the constructed type cannot be reassigned.
Ejemplo en Entorno de Trabajo:
Cuando quieres asegurar que ciertos objetos no sean modificados una vez creados,
como configuraciones o constantes.
*/

type GiftCard = {
to: string;
date: Date;
money: number;
};

const sarahsGift: Readonly<GiftCard> = {
to: "Sarah",
date: new Date(),
money: 200,
};

console.log("sarahsGift :>> ", sarahsGift);

// sarahsGift.date = new Date(); // No podemos reasignar el valor de la propiedad date
29 changes: 29 additions & 0 deletions stuff/ts/src/utility-types/Required.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/* Constructs a type consisting of all properties of Type set to required. The
opposite of Partial.
RequiredUser obliga a que todas las propiedades sean proporcionadas.
Ejemplo en Entorno de Trabajo:
Al recibir datos de una API externa donde algunos campos opcionales deben ser
tratados como requeridos en tu aplicación.
*/

type Client = {
name: string;
isOnline: boolean;
typeOfService: "premium" | "basic" | "pro";
};

type RequiredClient = Required<Client>;

function createClient(client: RequiredClient): Client {
return client;
}

const basicClient = createClient({
name: "Jasmine",
isOnline: true,
typeOfService: "basic",
});

// const badClient = createClient({ name: "Julius", isOnline: false }); // Falla porque todas las propiedades de Client son obligatorias
2 changes: 1 addition & 1 deletion stuff/ts/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "stuff/ts/dist" /* Specify an output folder for all emitted files. */,
"outDir": "dist" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
Expand Down

0 comments on commit 36202b9

Please sign in to comment.