In the previous class, we set up our development environment and delved into Typescript's Primitive Types.
In today's class, we will learn how to work with Objects and Arrays in Typescript.
In this class, we will learn about Objects and Arrays in Typescript. Let's explore different ways in which we can create objects and arrays in our projects with Typescript.
One of the simplest ways to create an object is through object literals. This approach is particularly useful when you already have prior knowledge of the object's properties, as you cannot add new properties later.
const objeto = { chaveA: 'value', chaveB: 'value', }; objeto.chaveC = 'value';
One way to create dynamic objects is using Index Signature. This approach is especially useful when we don't know in advance what the object's properties will be.
const objeto: { [key: string]: string } = { chaveA: 'value A', chaveB: 'value B', }; objeto.chaveC = 'value C'; console.log(objeto);
Another way we can create dynamic objects in Typescript is using Record. Record is one of the Utility Types in the Typescript toolbox. Let's explore more about Utility Types later. For now, what you need to know is that when using Record, we need to specify the type for the key and the value of the object between <>.
const objeto: Record<string, string> = { chaveA: 'value A', chaveB: 'value B', };
The simplest way to create an array is using a literal array, which is a comma-separated list of elements enclosed in square brackets.
const arrayDeNumeros: number[] = [1, 2, 3]; const arrayDeString: string[] = ['Josh', 'Patrick', 'Lamar']; const arrayDeStringENumeros: (string | number)[] = [1, 'Alice', 55]; console.log(arrayDeString); console.log(arrayDeNumeros); console.log(arrayDeStringENumeros);
You can also use the Array constructor to create a new array.
const arrayDeNumeros: Array<number> = [1, 2, 3]; const arrayDeString: Array<string> = ['Josh', 'Patrick', 'Lamar']; const arrayDeStringENumeros: Array<string | number> = [1, 'Alice', 55]; console.log(arrayDeString); console.log(arrayDeNumeros); console.log(arrayDeStringENumeros);
You can access the class code by accessing the link below:
https://github.com/d3vlopes/curso-typescript/tree/aula-002
In the next class, we will explore functions in Typescript. Let's learn how to define parameter types, return types and more!
Leave a comment and share this post with your network to support and help more people learn Typescript.
The above is the detailed content of Free Typescript Classroom Course. For more information, please follow other related articles on the PHP Chinese website!