@@ -13,21 +13,36 @@ const names: string[] = ['Alice', 'Bob', 'Charlie']
1313TypeScript offers two ways to write array types:
1414
1515``` ts
16- // Square bracket syntax (more common )
16+ // Square bracket syntax (shorter )
1717const numbers: number [] = [1 , 2 , 3 ]
1818
19- // Generic syntax
19+ // Generic syntax (preferred)
2020const numbers: Array <number > = [1 , 2 , 3 ]
2121```
2222
23- Both are identical—use whichever you prefer, but be consistent.
23+ Both are functionally identical. The square bracket syntax is shorter and you'll
24+ see it frequently in codebases. However, the generic syntax (` Array<Type> ` ) is
25+ preferred for several reasons:
26+
27+ - ** Readability** : We read left-to-right, so "Array of numbers" reads more
28+ naturally than "numbers... array"
29+ - ** Consistency with readonly** : ` ReadonlyArray<string> ` vs ` readonly string[] `
30+ - ** Union types** : ` Array<string | number> ` vs ` (string | number)[] ` (no
31+ parentheses needed)
32+ - ** Works better with ` keyof ` ** : Avoids confusing operator precedence issues
33+
34+ For a deeper dive into why generic notation is better, check out
35+ [ Array Types in TypeScript] ( https://tkdodo.eu/blog/array-types-in-type-script )
36+ by TkDodo.
37+
38+ We'll use the generic syntax going forward in this workshop.
2439
2540## Type Safety with Arrays
2641
2742TypeScript ensures you only put the right types in arrays:
2843
2944``` ts
30- const numbers: number [] = [1 , 2 , 3 ]
45+ const numbers: Array < number > = [1 , 2 , 3 ]
3146numbers .push (4 ) // ✅ OK
3247numbers .push (' five' ) // ❌ Error: 'string' not assignable to 'number'
3348```
@@ -38,11 +53,11 @@ You can add elements to arrays in two ways:
3853
3954``` ts
4055// Mutation (modifies the original array)
41- const numbers: number [] = [1 , 2 , 3 ]
56+ const numbers: Array < number > = [1 , 2 , 3 ]
4257numbers .push (4 )
4358
4459// Immutable (creates a new array)
45- const numbers: number [] = [1 , 2 , 3 ]
60+ const numbers: Array < number > = [1 , 2 , 3 ]
4661const moreNumbers = [... numbers , 4 ]
4762```
4863
6378Need different types? Use union types:
6479
6580``` ts
66- const mixed: ( string | number )[] = [1 , ' two' , 3 , ' four' ]
81+ const mixed: Array < string | number > = [1 , ' two' , 3 , ' four' ]
6782```
6883
6984In this exercise, you'll create and work with typed arrays.
0 commit comments