This lesson explores managing arrays and objects in TypeScript, emphasizing type safety and proper initialization to avoid compilation errors.
In this lesson, we explore how to work with arrays and objects in TypeScript. Elmer encounters a situation where he needs to manage multiple objects together, and TypeScript offers robust tools to handle this seamlessly.
When creating an array in TypeScript, it’s best practice to explicitly define its element type. For example, if you have an array of duck names (strings), you can define it as follows:
Elmer also needs to store detailed information about each duck, including properties such as its type and color. Objects enable you to group related key-value pairs into a single entity. Consider the following example, which represents a duck:
Here, the keys—name, age, type, and color—accompany their respective values, offering a structured way to represent data. To access a specific property of this object, you can use dot notation. For example, to print the duck’s name to the console, you would write:
Copy
Ask AI
console.log(duck.name);
When this code is compiled and executed, “Daffy” is logged to the console.
Always initialize your declarations properly. Failing to initialize objects or misspelling property names leads to compilation errors.
If you omit initializing an object during its declaration, TypeScript will report errors similar to:
Copy
Ask AI
[ERROR] 19:49:42 × Unable to compile TypeScript:index.ts(1,7): error TS1155: 'const' declarations must be initialized.index.ts(1,7): error TS7005: Variable 'duck' implicitly has an 'any' type.
Similarly, accessing a non-existent property will lead to errors like:
Copy
Ask AI
[ERROR] 19:50:10 × Unable to compile TypeScript:index.ts(3,9): error TS2339: Property 'l' does not exist on type 'Console'.
These messages serve as helpful reminders to access only the defined properties and to maintain proper initialization.