me: adding //@ts-check
my brain:
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
Static code analysis will help us to detect flaws in our program during its development.
In the src
folder of the course project, we are going to create a JavaScript file called demo.js.
The code base is as follows:
(()=> { const myCart = []; const products = []; const limit = 2; async function getProducts() { const rta = await fetch('http://api.escuelajs.co/api/v1/products', { mehtod: 'GET'}); const data = await rta.parseJson(); products.concat(data); } function getTotal() { const total = 0; for (const i = 0; i < products.length(); i++) { total += products[i].prize; } return total; } } function addProduct(index) { if (getTotal <= limit) { myCart.push(products[index]); } } } await getProducts(); addProduct(1); addProduct(2); const total = getTotal(); console.log(total); const person = { name: 'Nicolas', lastName: 'Molina'} const rta = person + limit; console.log(rta); });
When analyzing it we realize that it has some errors that could go unnoticed as we do not see warnings. It is until we run it in a web browser or environments like NodeJS that the bugs will come to light. So, we as developers, this is not convenient, as we want feedback as soon as possible.
If you are in Visual Studio Code, you can activate the TypeScript static code analyzer on a JavaScript file. To do this, on the first line of the file should go the following:
//@ts-check
Contributed by: Martin Alvarez.
Contributions 68
Questions 10
me: adding //@ts-check
my brain:
Creo que así quedaría el código arreglado:
Por cierto, les recomiendo muchísimo la extensión de Error Lens para tener también un feeback muy llamativo y detallado de los errores en código.
//@ts-check
(async ()=> {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch('https://api.escuelajs.co/api/v1/products', {
method: 'GET'
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
/**
* @param {number} index
*/
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
const rta = `${person} - ${limit}`
console.log(rta);
});
Dato: El @ts-ckech es de Viscual studio, una de las ventajas que nos da trabajar typescript con ese gran editor.
Fuente: Clic aquí.
“feedback temprano” ame esa frase
En esta clase nos dimos cuenta de porque TS se esta volviendo tan usado en la industria
Si instalan la extension Error Lens les va a mostrar los errores mas bonito, el codigo jodido pero siempre facherito.
.
//@ts-check nos da feedback y análisis de typescript.
“feedback temprano”.
Activando Typescript check en la primera linea del codigo:
//@ts-check
Qué manera más gráfica de ver el porqué debemos utilizar TS.
Resuelto:
(async ()=> {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch('https://api.escuelajs.co/api/v1/products', {
method: 'GET'
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
const rta = {
...person,
limit: limit
}
console.log(rta);
});
Aquí esta mi codigo, incluye manipulación del DOM para agregar a div la constante rta.
(async ()=> {
const myCart = [];
const products = [];
const limit = 2246934;
const url = ''
async function getProducts() {
const rta = await fetch(url, {
method: 'GET'
});
const data = await rta.json();
data.forEach(element => {
products.push(element)
});
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].price;
}
return total;
}
function addProduct(index) {
if (getTotal.length <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
const rta = `Hey ${person.name} ${person.lastName}!, you have ${myCart.length} items in your cart`;
console.log(rta);
//Para renderizar en HTML datos de Nicolas
const el = document.getElementById('content');
el ? el.textContent = rta : "";
})();
Les recomiendo la extensión de VSCode Error Lens (bajen el que más descargas tenga), al combinarla con //ts-check les da esto:
Luego de ver este video.
Mi cerebro:
En Visual Studio Code pueden instalar la extensión llamada Error Lens usernamehw.errorlens
que les muestra mensaje de error en el editor sin necesidad colocar el cursor del mouse encima del codigo con el error.
Es extraña la forma de activar el ANALIZADOR DE CODIGO ESTATICO de TS:
//@ts-check
Es decir, como si se tratara de un comentario.
Recomendado este plugin de VSCode: TypeScript Error Translator
Les dejo la solución, solo le agregan la URL de la Api, ya que platzi no me permite subirlo
//@ts-check
(async ()=> {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch('', {
method: 'GET'
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal.length <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
const rta = `${person.name} ${person.lastName} ${limit}`;
console.log(rta);
});
My solution to the end part
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
const rta = `${person.name} ${person.lastName} ${limit}`;
console.log(rta);
excelente curso
//@ts-check
(async ()=> {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = , {
method: ‘GET’
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: ‘Nicolas’,
lastName: ‘Molina’
}
const rta = person.limit + limit;
console.log(rta);
});
✅
Da un error en prize 😦
Más o menos así me quedó debuggeado el código.
//! Code debugged
const myCart = []
const products = []
const limit = 2
const getProducts = async () => {
try {
const response = await fetch(url, {
method: 'GET'
})
if (response.ok) {
const data = await response.json()
products.concat(data)
} else {
`${response} The response has been declined by the server`
}
} catch (error) {
console.error(`Error un the getProducts function, ${error}`)
}
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total = + products[i].prize;
}
return total;
}
const addProducts = async (index) => {
const total = await getTotal
if (total <= limit) {
myCart.push(products[index]);
}
}
const main = async () => {
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
await getProducts()
addProducts(1);
addProducts(2);
}
TypeScript te amo!, para mi siempre fue un problema que javascript no mostrara errores tan básicos y esto soluciona y agiliza mucho el desarollo
demo.js:
//@ts-check
(async ()=> {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch('/api/v1/products', {
method: 'GET'
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
const rta = person.length + limit;
console.log(rta);
});
//@ts-check
(async()=> {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch(, {
method: 'GET'
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
const rta = person.stringyfy + limit;
console.log(rta);
});
reto completado
Por alguna razón no me está funcionando @ts-check
Casi quedo ciego con tanto rojo pero ya 😄
//@ts-check
async () => {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch("https://platzi.com", {
method: "GET",
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (total <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: "Nicolas",
lastName: "Molina",
};
const rta = person.name + limit;
console.log(rta);
};
async no se dice “asainc” se dice como suena. Aquí la pronunciación de la palabra sync (abreviatura de synchronous) :https://www.google.com/search?rlz=1C5CHFA_enCO1016CO1016&sxsrf=AJOqlzWfNtZf48B355aSuOOgjt7ZN3FNvQ:1677683628107&q=how+to+pronounce+sync&stick=H4sIAAAAAAAAAOMIfcRoxi3w8sc9YSndSWtOXmNU5-INKMrPK81LzkwsyczPExLgYglJLcoV4pBi42IprsxLtmJRYkrN41nEKpqRX65Qkq9QAFSfD9SQqgCSBgBzzL3uUwAAAA&pron_lang=en&pron_country=gb&sa=X&ved=2ahUKEwjPgcvFgrv9AhWuSzABHRkNBvEQ3eEDegQICBAK
//@ts-check
(async ()=> {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch('https://api.escuelajs.co/api/v1/products', {
method: 'GET'
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
const rta = `${person.name} ${person.lastName} - ${limit}`;
console.log(rta);
});
//@ts-check
async () => {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch("https://platzi-avo.vercel.app/api/avo", {
method: "GET",
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].price;
}
return total;
}
function addProducto(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProducto(1);
addProducto(2);
const total = getTotal();
console.log(total);
const person = {
name: "Nicolas",
lastName: "Molina",
};
let rta = `Hola ${person.name} ${person.lastName} - ${limit}`;
console.log(rta);
};
Ya no me sale que haya ningún error, espero que esté correcto 🤗
me gusto mucho esta clase!
No sé si resuelve el problema porque ni conozco cual es el problema pero, deja de marcar todo rojo:
(async () => {
const myCart = [];
const products = [];
const limit = 2;
const API: "api.escuelajs.co/api/v1/products";
async function getProducts() {
const rta = await fetch(API, {
method: 'GET'
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
const rta = { ...person, "limit": limit };
console.log(rta);
});
<code>
//@ts-check
(async ()=> {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch('htp://api.escuelajs.co/api/v1/products', {
method: 'GET'
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
const rta = `${person} - ${limit}`;
console.log(rta);
});
El profe dice que no analise el codigo. Es como que me digan que no piense en un elefante blanco, XD
El aporte:
//@ts-check
async () => {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch("ht tp://api.escuelajs.co/api/v1/products", {
method: "GET",
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: "Andrés",
lastName: "Eslava",
};
const rta = `${person.name} - ${limit}`;
console.log(rta);
};
yo tengo instalado el paquete para la interfaz en español de VScode, las explicaciones de los errores también me salen en español :’)
para eso ocupo una extensión Error Lens
es buena
y fuera de marcarlo en la barra de desplazamiento te lo marca al lado del código mal escrito
El ejercicio corregido:
//@ts-check
(async()=> {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch('https://api.escuelajs.co/api/v1/products', {
method: 'GET'
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
const rta = `${person.name} ${person.lastName} ${limit}`;
console.log(rta);
});
Aquí esta la solución espero que les sirva
solo coloquen la ruta en fetch ya que el comentario no mejo colocarlo
//@ts-check
(async ()=> {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch(’ ', {
method: ‘GET’
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
let person = {
name: ‘string’,
lastName: ‘string’
}
const rta = person + limit;
console.log(rta);
});
El aporte:
//@ts-check
async () => {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch("ht tp://api.escuelajs.co/api/v1/products", {
method: "GET",
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: "Andrés",
lastName: "Eslava",
};
const rta = `${person.name} - ${limit}`;
console.log(rta);
};
se podria decir que un TesterQA es un posible evangelizador de TypeScript?? je
Cada cosa nueva que aprendo en estas clases es un mundo, pero es un mundo bonito xD
Te recomiendo la extensión de **VSCode ** llamada Error Lens que te dará un mejor feedback en español sobre lo que ocurre, si lo combinas con //@ts-check
verás algo así:
Mi solución
//@ts-check
(async()=> {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch('platzinodejaponerlink', {
method: 'GET'
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
const rta = `${person.name} ${person.lastName} - ${limit}`;
console.log(rta);
})();
ya me encantoooooooo!!!
0 problemas detectados
//@ts-check
(async () => {
const myCart = [];
const products = [];
const limit = 2;
async function getProducts() {
const rta = await fetch('https://api.escuelajs.co/api/v1/products', {
method: 'GET'
});
const data = await rta.json();
products.concat(data);
}
function getTotal() {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i].prize;
}
return total;
}
function addProduct(index) {
if (getTotal() <= limit) {
myCart.push(products[index]);
}
}
await getProducts();
addProduct(1);
addProduct(2);
const total = getTotal();
console.log(total);
const person = {
name: 'Nicolas',
lastName: 'Molina'
}
const rta = person.name + limit;
console.log(rta);
});
TS se puede complementar de forma muy interesante con el plugin de VS llamado ‘Error Lens’ funciona muy cool ya que te dice el tipo de error que se esta presentando en la linea del error. 😉
Instalen la extensión error lens. El error se muestra n línea y da feedback muy cómodamente.
Eslint y prettier te ayuda mucho a analizar código JS en tiempo real!
Para analizar errores en un archivo JS podemos colocar esto al inicio: //@ts-check
Los superpoderes de TypeScript
En vsc instalar: version lens, error lens y add en la primera linea el siguiente comentario:
//@ts-check
Analizador de TS en JS, lo podemos usar en archivos JS así:
//@ts-check
Me encantó esta clase!
ESLint, es la extensión de VS code que ayuda a marcar los errores con una linea roja debajo
Waaau, con razón Yo veía ese subrayado en el código de los profesores y pensaba, por qué será que les aparece? será una especie de corrector ortográfico? Ahora entiendo, qué emoción!
Want to see more contributions, questions and answers from the community?