You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
13 Hrs
52 Min
54 Seg
Curso de TypeScript

Curso de TypeScript

Nicolas Molina

Nicolas Molina

Arrays

12/24
Resources

It is an ordered collection of data. We define them as follows:

let prices = [1,2,3,4,5];/* Push method to add an element to the end of the array */prices.push(6);console.log(prices); // [1,2,3,4,5,6].

For the array prices, TypeScript, if not explicitly indicated, will infer that it will only contain values of type number, so if you want to add a string value, for example, it will indicate an error:

//TypeScriptprices.push("text"); //ERROR.  It is expected to add only numbers to the array.

This is because in its initialization it was assigned an array that only contained numbers.

It will also indicate us error if we pretend to make exclusive operations of a data type over the one of another type:

let months = ["May","June","July"]; months.map( item => item * 2 ); //ERROR.  You are trying to perform a multiplication using strings.

Array typing in TypeScript

You can define it like this:

  • Explicitly state the data types that the array will store:
let prices: (number | string)[] = ["hello",2,4,6,"world"];let otherPrices: (boolean | number)[];

For this case, unless the variable is a constant, you do not need to initialize the variable, since you have already specified the data type.

  • In the initialization of the variable, place data with the data type that you want your array to support from now on so that TypeScript can infer it:
//TypeScriptlet prices = ["hello",2,4,6,"world"];// "hello", "world" => string// 2,4,6 => number.

We make it clear that we want it to support both string and number data types.

Contribution created by: Martin Alvarez.

Contributions 21

Questions 5

Sort by:

Want to see more contributions, questions and answers from the community?

el curso de manipulación de arrays es buenísimo …

📌📍📝 ==> La forma correcta de asignarle el tipo a un array cuando contiene numeros, strings y booleans es:

let prices: (number | string | boolean)[]

Creo que al profe se le paso el Object con mayuscula.

recordemos la diferencia entre object y Object.

recordemos que object es el correcto, por que nos va a diferenciar entre datos primitivos (number, string, boolean, etc) y todo lo que no sea esto, puede caber dentro de object.

Documentacion oficinal de typescript

(() => {
    const prices = [1,2,3,4,5,6, 'hola', true];

    //lo que no puedo hacer
    // prices.push('jkgdsakjgd');
    // prices.push(true);
    // prices.push({});

    prices.push(12313131);
    let products = ['hola', true];
    products.push(false);

    //para escribir booleans, numbers y strings hay que hacerlo de forma explicita
    //se puede usar | objecta y acepta arrays y objetos pero para eso hay un modulo más adelante
    const mixed: (number | string | boolean)[] = ['hola', true];
    //ahora si me deja ingresar números 
    mixed.push(12);

    let numbers = [1,2,3,4,5,6,7,8];
    numbers.map(item => item * 2); 
    console.log(numbers);
})();

Resumen de la clase

Cuando creamos el siguiente array de puros numeros

const numbers = [1, 2, 3, 4, 5]

TS infiere que el tipo es number[]. Si lo quisieramos hacer de manera explicita seria asi

const numbers: number[] = [1, 2, 3, 4, 5]

.
Cuando agregamos mas de un tipo de dato en un array, TS lo infiera de esta manera

const arr: (number | boolean | string)[] = [1, true, "str"]

.
Por ultimo, cuando un array contiene otros arrays u objetos podemos usar el tipo de dato Object

const arr: Object[] = [{}, [], {}, []]

Usando Object, me permitió usar el tipo Boolean sin habérselo dicho:

.
Usando object, ya reaccionó como era y no me lo permitió:

Escriban lo siguiente en chatGPL y vean la magia:

Creame un snippet para declarar un array en ts que reciba todo tipo de datos y nombralo como “universalarray”

object !== Object ?

const numeros: number[] = [1, 2, 3, 4, 5];

//@ts-ignore: Esto da error porque un array de números no acepta textos
numeros.push('hola');


const cadenas : string[] = ['Hola', 'que tal', 'bien', 'chau'];

//@ts-ignore: Esto también da error por lo mismo en este caso de strings
cadenas.push(1);


//Más de un tipo de dato

    const poblationCountries : (string | number)[] = ["Paraguay", 7000000, "Uruguay", 4000000];

    //@ts-ignore: Da error porque no lo pusimos en el mixin de datatypes
    poblationCountries.push(true);


//La forma implícita es la más recomendable siempre y cuando se pueda

const inferedNumbers = [1, 2, 3, 4, 5];

//@ts-ignore: Esto da error igual de forma inferida
inferedNumbers.push('hola');


const inferedStrings = ['Hola', 'que tal', 'chau'];

//@ts-ignore: Esto da error igual de forma inferida
inferedStrings.push(1);

//Más de un tipo de dato

    const inferedPoblationCountries = ["Paraguay", 7000000, "Uruguay", 4000000];

    //@ts-ignore: Da error porque no lo pusimos en el mixin de datatypes
    inferedPoblationCountries.push(true);

La forma correcta de asignarle los tipos que admite un array es la siguiente, así evitamos que la variable prices no sea usada como array

    let prices:Array<number|string> = [1,2,3,4,5,6,7,8];
    prices.push('string');
    prices.push(1); //number

Como aprendizaje esta bien, aunque creo que es una mala practica mezclar tipos de datos en un array.

alt + 1 = | (pipe) en Mac

lo primero que se me vino a la mente es... Como hago para crear un array y saberlo tipar sin saber que datos me vendrían de la API? Luego entendi el punto del tipado JAJAJAJA
El curso de manipulación de arrays en JavaScript: <https://platzi.com/cursos/arrays/>

Arrays dentro de arrays 👈👀🔥

El profe mostró algunas formas de meter un array dentro de otro, pero prueba esta:

// Al hacer esto ...
let mixed_one = [1, 2, 3, 'x', true, [1, true, 'x']];

// El editor muestra esto:
let mixed_one: (string | number | boolean | (string | number | boolean)[])[]

Interesante, ¿no? 😅

hay que tener en cuenta 2 cosas:

  • cuando creamos un arreglo vacío sin asignarle tipos de dato
let arr = []

por defecto, Typescript les asignara como tipo de dato any, el cual acepta cualquier tipo de valor

  • Object es diferente a object, Object acepta cualquier tipo de dato, sea o no primitivo

object, por el contrario, solo acepta tipos de datos no primitivos, como los arrays y objetos

Este es el curso del que habla el profesor Curso de Manipulación de Arrays en JavaScript

Si hay un curso que me ha servido muchísimo en la practica como desarrollador frontend, es el curso de manipulación de arrays, lo super recomiendo.

Llegando al final de este primer modulo te comparto estas notas que encontre en Medium que estan muy utiles

https://medium.com/@roperluo.me/typescript-types-study-notes-3060f9bf48af

Tambien podemos expresar con any, de esta forma indicamos que puede tener cualquier tipo de dato

let myList: any = [];


myList.push('fabio', 28, {lastname:'sosa'})