lo del minuto 11:30 se puede hacer con el mismo visual estudio code con click derecho cambiar el nombre del simbolo o la tecla f2
Introducción a TypeScript
Por qué usar TypeScript
TypeScript vs. JavaScript
Configurado nuestro proyecto
Atrapando bugs
El compilador de TypeScript
Veamos el TSConfig.json
Tipos de datos primitivos
Qué es el tipado en TypeScript
Tipos inferidos
Numbers
Booleans
Strings
Arrays
Tipos de datos especiales
Any
Union Types
Alias y tipos literales
Null y Undefined
Funciones
Retorno de funciones
Objetos en funciones
Objetos como tipos
Módulos: import y export
Usando librerías que soportan TypeScript
Usando librerías que NO soportan TypeScript
Próximos pasos
Toma el Curso de Tipos Avanzados y Funciones en TypeScript
You don't have access to this class
Keep learning! Join and start boosting your career
Our code can be divided into several modules (files), so in order to use the functions or variables that exist in one and we want to access from another, we use import
and export
.
/*----> File: functions.ts <----*/export function sum(a: number, b: number): number { return a + b; }export function subtract(a: number, b: number): number { return a - b; }export let numerosRandom = [1, 30, 40, 50];export type Sizes = "S" | "M" | "L" | "XL";
As we can see, we have a file called functions.ts
which contains two functions: addition and subtraction. If we want to use them from another file, we need to use the reserved word export
just before defining our function (the same applies for variables). This way we indicate that they will be exported to be used from another JavaScript/TypeScript file.
/*---> File: program.ts <---*/import {sum, subtract, Sizes} from "./functions.ts";
Finally, the functions or variables that we want to use from another file are imported as follows:
import
from
, followed by, between double or single quotes, the path to the location of the file from which we are importing its code.If it is a TypeScript module that we are importing, it is important that the path of the import contains the .ts
extension of that file. If it is a JavaScript file, placing the .js
extension is optional.
Contribution created by: Martin Alvarez.
Contributions 18
Questions 8
lo del minuto 11:30 se puede hacer con el mismo visual estudio code con click derecho cambiar el nombre del simbolo o la tecla f2
Para no repetir el export se puede exportar todo junto al final del archivo como un objeto
type Sizes = 'S' | 'M' | 'L' | 'XL';
type Product = {
title: string,
createdAt: Date,
stock: number,
size?: Sizes
}
export {
Sizes,
Product,
}
Otra manera de escribir “calcStock” usando reduce:
import {Product} from './product.model'
const products: Product[] = []
const addProduct = (data: Product) => products.push(data)
const calcStock = ():number => products.reduce((acc, product) => acc + product.stock, 0)
export {products, addProduct, calcStock}
Podemos concluir que para crear módulos, solo tenemos que exportar ciertas variables de cualquier archivo e importarlas en otros.
.
También podemos notar que los alias pueden ir en su propio archivo, para que puedan ser importados en todos los demás archivos que los ocupen.
Excelente clase 👏
Class
product.model.ts
import { createProduct, calcStock, products } from "./product.service";
createProduct({
name:"Pro1",
createdAt:new Date(1993,1,1),
stock:5
});
console.log(products);
createProduct({
name:"Pro2",
createdAt:new Date(1993,1,1),
stock:6,
size:"XL"
});
console.log(products);
const total = calcStock();
console.log(total);
product.service.ts
import { product } from "./product.model";
export const products:product[]=[];
export const createProduct=(data:product) =>{
products.push(data);
}
export const calcStock = ():number => {
let total = 0;
products.forEach((item)=> {
total += item.stock;
});
return total;
};
main.ts
import { createProduct, calcStock, products } from "./product.service";
createProduct({
name:"Pro1",
createdAt:new Date(1993,1,1),
stock:5
});
console.log(products);
createProduct({
name:"Pro2",
createdAt:new Date(1993,1,1),
stock:6,
size:"XL"
});
console.log(products);
const total = calcStock();
console.log(total);
Esto es genial!!!
Como comentan varios compañeros podemos exportar todas las funciones al final del código como si fuera un objeto
.
import { Product } from './product.model';
// .service <name_convention> relates to the Methods or Data treatment
const products: Product[] = [];
const addProduct = (data: Product) => {
products.push(data);
};
const inStock = (): number => {
// Oportunidad para Refactorizar con los métodos de Arrays
// Curso en platzi :)
const total = 0
products.forEach(item => total += item.stock)
return total;
};
export { products, addProduct, inStock };
Vemos que ya queda todo de manera organizada, pero ese forEach 🤔 asignando una variable por fuera…
Podemos ver el curso Manipulación de Arrays y pasar a tener algo como esto:
const inStock = (): number => {
// Manipulación de Arrays
return products.reduce((prev, current) => prev + current.stock, 0);
};
Espero les motive a seguir aprendiendo y también más importante aún apoyar a los compañeros dentro y fuera de clase. ✨
Si alguno tiene problemas con la importación y le arroja un error tipo este
(node:36128) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
deben agregar a su configuración en package.json
"type":"module",
Y si luego de esto obtienen otro error como este:
node:internal/errors:484
ErrorCaptureStackTrace(err);
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\Intel\Documents\github\tsproject\dist\user.services' imported from C:\Users\Intel\Documents\github\tsproject\dist\executable.js
at new NodeError (node:internal/errors:393:5)
at finalizeResolution (node:internal/modules/esm/resolve:323:11)
at moduleResolve (node:internal/modules/esm/resolve:916:10)
at defaultResolve (node:internal/modules/esm/resolve:1124:11)
at nextResolve (node:internal/modules/esm/loader:163:28)
at ESMLoader.resolve (node:internal/modules/esm/loader:841:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
at link (node:internal/modules/esm/module_job:75:36) {
code: 'ERR_MODULE_NOT_FOUND'
}```
la solución que conseguí fue esta configuración en tsconfig.json -> de esta forma completa la extensión en el path del import
{
“compilerOptions”: {
“target”: “ES2022”,
“outDir”: “./dist”,
“rootDir”: “./src”,
“module”: “ES2022”,
“esModuleInterop”: true,
“strict”: true
},
“include”: [“src/**/*.ts”],
“exclude”: [“node_modules”]
}
El proceso de módulos en TS es algo similar a trabajar en el framework de Spring creando APIs
✅
Tengan cuidado con las comillas, no se puede importar con las siguientes comillas `` (inversas) , pero si con estas ’ '.
aaaaaaaaaa ya voy entendiendo como para que sirven los framworks jejejej
Una alternativa para sumar el stock!
export const calcStock = (): number => {
return productos
.map((item) => item.stock)
.reduce((accu, curren) => accu + curren);
};
El ultimo problema se puede solucionar sin necesidad de cambiar el atributo en cada archivo que lo requiere, creando una nueva variable en el scope de la función que su nombre en name y su valor title, la retornamos al backend con su respectivo nombre sin necesidad de cambiar en cada archivo, esto puede ser una mala practica porque “no se manejarían los mismo valores”
({
title: string
// ...
}) {
let name = title
// ...
}
Con Javascript también se puede. Con extensiones .mjs.
Want to see more contributions, questions and answers from the community?