'readonly' Modifier for Arrays
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 14 of 73.
TypeScript provides the readonly modifier for arrays, which prevents any changes to the array's contents once it's created.
When you add readonly before an array type, TypeScript ensures that you cannot add, remove, or modify elements. This creates an immutable data structure that's perfect for configuration data, constants, or any situation where you want to guarantee the array won't change.
let colors: readonly string[] = ["red", "green", "blue"];
let numbers: readonly number[] = [1, 2, 3, 4, 5];The readonly modifier blocks all mutating operations like push(), pop(), splice(), and direct index assignment. If you try to use these methods, TypeScript will show a compile-time error, preventing potential bugs before your code runs.
Challenge
EasyCreate a readonly array named configValues that can only hold strings and initialize it with the values "production", "database", and "cache".
Then create another readonly array named ports that can only hold numbers and initialize it with the values 3000, 5432, and 6379.
Finally, create a readonly array named features that can only hold boolean values and initialize it with true, false, and true.
Print all three readonly arrays to the console on separate lines in the order they were created.
Try it yourself
// TODO: Write your code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples