Typescript Array
Array Typing in TypeScript
TypeScript allows you to define arrays with precise value types to help maintain data consistency.
Defining Typed Arrays
You can declare arrays that are restricted to storing specific data types. This helps prevent unexpected inputs at runtime.
Illustration:
const students: string[] = [];
students.push("Liam");
This ensures your array only holds the data type you intended — nothing more, nothing less.
Immutable Arrays with readonly
To avoid accidental modification, mark your array as readonly. This disables mutation methods like push, pop, etc.
Example:
const fruits: readonly string[] = ["Apple"];
fruits.push("Banana");
You can try removing the readonly keyword to see how mutability is restored.
Letting TypeScript Infer the Array Type
When you provide initial values, TypeScript can automatically determine the type of the array based on those values.
Snippet:
const primes = [2, 3, 5];
Primes.push(7); primes.push("eleven");
let smallestPrime: number = primes[0];
This makes your code more concise without sacrificing type safety.
Let me know if you'd like an extension on:
- Multi-dimensional arrays
-
Using Array
instead of T[] - Array methods with strong typing
- Filtering or mapping arrays in TS
Prefer Learning by Watching?
Watch these YouTube tutorials to understand TYPESCRIPT Tutorial visually:
What You'll Learn:
- 📌 TypeScript tutorial for beginners #6 Array
- 📌 TypeScript Tutorial #4 - Objects & Arrays