Skip to content

Commit

Permalink
add Partial and Record utilty types b00tc4mp#1
Browse files Browse the repository at this point in the history
  • Loading branch information
frankpereiragomez committed Nov 20, 2024
1 parent 36202b9 commit 613d7e0
Show file tree
Hide file tree
Showing 5 changed files with 162 additions and 7 deletions.
70 changes: 68 additions & 2 deletions stuff/ts/src/utility-types/Partial.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,78 @@ const updateTodo = (todo: Todo, filesToUpdate: Partial<Todo>): Todo => {

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

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

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

//TODO Actualizar el perfil de un usuario
//Actualizar el perfil de un usuario

type User = {
readonly id: number;
name: string;
surname: string;
isLazy: boolean;
};

const users: User[] = [
{
id: 1,
name: "Dinosauirios",
isLazy: true,
surname: "de Vainilla",
},
{
id: 2,
name: "Camioncito",
isLazy: false,
surname: "pegriloso",
},
{
id: 3,
name: "Pototype",
isLazy: true,
surname: "Jonas",
},
{
id: 4,
name: "handelel",
isLazy: false,
surname: "and gretelel",
},
];

const getUserById = (usersArray: User[], userId: number): User | null => {
const user = usersArray.find(({ id }) => id === userId);

if (!user) {
throw new Error("User not found");
}

return user;
};

type UserWithoutId = Omit<User, "id">;

const updateUser = (propsToUpdate: Partial<UserWithoutId>): void => {
const userToUpdate = getUserById(users, 2);

if (!userToUpdate) {
throw new Error("User not found");
}

const userIndex = users.findIndex(({ id }) => id === userToUpdate.id);

users.splice(userIndex, 1);

const updatedUser = { ...userToUpdate, ...propsToUpdate };

users.push(updatedUser as User);
};

updateUser({ name: "misegundocamionsito", surname: "peroenrefrigerio" });

console.log("users :>> ", users);
2 changes: 1 addition & 1 deletion stuff/ts/src/utility-types/Pick.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ type TaskResume = Pick<Task, "description" | "isCompleted">;

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

console.log("studyTypescript :>> ", studyTypescript);
91 changes: 91 additions & 0 deletions stuff/ts/src/utility-types/Record.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/* Record<Keys, Type>
Constructs an object type whose property keys are Keys and whose property values are Type.
This utility can be used to map the properties of a type to another type.
El utility type Record<K, T> es un tipo genérico en TypeScript que te permite crear un tipo de objeto
cuyas claves son de tipo K y cuyos valores son de tipo T. En otras palabras, Record te permite crear
mapas o diccionarios tipados, donde especificas el conjunto de claves permitidas y el tipo de los valores
asociados a esas claves.
Piensa en Record<K, T> como un molde genérico para crear objetos donde las claves son un conjunto específico
y los valores tienen un tipo común.
Usar Record es como decir: "Quiero un objeto que tenga exactamente estas claves, y todos sus valores serán
de este tipo".
Usa Record<K, T> cuando:
Las claves provienen de otro tipo (como una unión de strings).
Quieres asegurar que todas las claves del conjunto estén presentes.
Necesitas flexibilidad y evitar repetición de código.
Usa type o interface cuando:
Las claves y sus tipos son fijos y conocidos.
Las propiedades pueden tener tipos diferentes.
Necesitas aprovechar características específicas de interface, como la herencia múltiple.
*/

type Role = "admin" | "editor" | "viewer" | "root";

type Permissions = Record<Role, { canEdit: boolean; canDelete: boolean }>;

// const rolesArray = ["admin", "editor", "viewer", "root", "super"] as const;
// type Role = (typeof rolesArray)[number];

const permissions: Permissions = {
admin: { canDelete: true, canEdit: true },
viewer: { canDelete: false, canEdit: false },
editor: { canDelete: false, canEdit: true },
root: { canDelete: true, canEdit: true },
};

const languagesCollection = ["en-US", "es-ES", "fr-FR"] as const;

type Language = (typeof languagesCollection)[number];

type Messages = Record<Language, string>;

const greetings: Messages = {
"en-US": "Hi",
"es-ES": "Hola",
"fr-FR": "Bonjour",
};

//calculator object

type Operations = "sum" | "rest" | "divide" | "multiply";
type Calculate = (x: number, y: number) => number;

type Calculator = Record<Operations, Calculate>;

const calculator: Calculator = {
sum: (x, y) => x + y,
rest: (x, y) => x - y,
multiply: (x, y) => x * y,
divide: (x, y) => {
if (y === 0) {
throw new Error("Cannot divide a number between zero");
}

return x / y;
},
};

console.log("sum :>> ", calculator.sum(2, 4));
console.log("sum :>> ", calculator.rest(10, 2));
console.log("sum :>> ", calculator.sum(2, 4));
console.log("sum :>> ", calculator.sum(7, 3));

//TODO crear un event handler

type EventType = "click" | "hover" | "keypress";
type EventHandler = Record<EventType, () => void>;

const eventHandler: EventHandler = {
click: () => console.log("onClick"),
hover: () => console.log("onHover"),
keypress: () => console.log("onKeyPress"),
};

eventHandler.click();
2 changes: 0 additions & 2 deletions stuff/ts/src/utility-types/Required.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
/* 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.
Expand Down
4 changes: 2 additions & 2 deletions stuff/ts/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */

/* Language and Environment */
"target": "ES5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"target": "ES2015" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
Expand All @@ -27,7 +27,7 @@
/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
"moduleResolution": "node10" /* Specify how TypeScript looks up a file from a given module specifier. */,
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
Expand Down

0 comments on commit 613d7e0

Please sign in to comment.