TypeScript Arrays
A TypeScript array stores an ordered collection of values. Its type determines which values can be added, while a zero-based numeric index identifies each element. For example, a number[] can hold a student’s marks, and a string[] can hold student names.
TypeScript checks array operations during development and then compiles the code to JavaScript. The array itself therefore uses standard JavaScript array behavior at runtime.
- Declare a typed array
- Initialize a TypeScript array
- Read array elements
- Add, update, and remove elements
- Create an array of objects
- Copy an array
- Define multidimensional arrays
- Use TypeScript array methods
- Prevent array mutation with readonly types
- Review TypeScript array FAQs
Declare a Typed Array in TypeScript
An array variable can be declared with either the elementType[] notation or the generic Array<elementType> notation. The first form is commonly used for simple element types.
var array_name[:datatype]
varis a variable-declaration keyword. Modern TypeScript generally usesconstwhen the variable will not be reassigned andletwhen reassignment is required.array_namerepresents the variable used to reference the array.- The type must describe the elements and the array, such as
number[],string[], orArray<boolean>.
The following older declarations illustrate variables with omitted or scalar annotations:
var arr1
var arr2:string
var arr3:int
These declarations do not define typed arrays. In addition, int is not a built-in TypeScript type; TypeScript uses number for ordinary numeric values. Use an array type explicitly:
let scores: number[];
let names: Array<string>;
let flags: boolean[];
If a variable is declared without a type and without an initial value, TypeScript may not provide the intended element-level protection. An explicit type is preferable when initialization happens later.
Initialize a TypeScript Array
An array can be initialized in its declaration or assigned after a typed variable has been declared.
The general declaration-and-initialization form is:
var array_name[:array_data_type] = [element1, element2, . ., elmentN]
An array may also be assigned after declaration:
var array_name[:array_data_type]
array_name = [element1, element2, . ., elmentN]
Examples of initialized number and string arrays are:
var marks1 = [58, 68, 74, 88, 64, 90]
var marks2:number[] = [58, 68, 74, 88, 64, 90]
var marks3:number[]
marks3 = [58, 68, 74, 88, 64, 90]
var students:string[] = ["Roshan", "Aditya", "Anisha", "Midhuna"]
When an initialized array contains values of one type, TypeScript can usually infer its element type. For example, const marks = [58, 68] is inferred as number[]. An empty array should normally have an explicit annotation because its intended element type may not be apparent.
const cities: string[] = [];
cities.push("Chennai");
cities.push("Pune");
// cities.push(42); // Type error: number is not assignable to string
Read TypeScript Array Elements by Index
Use a zero-based index to access an array element. The first element has index 0, the second has index 1, and the final valid index is normally array.length - 1.
example.ts
var marks:number[] = [58, 68, 74, 88, 64, 90]
console.log(marks[0])
console.log(marks[1])
console.log(marks[2])
console.log(marks[3])
Output
58
68
74
88
This array contains six elements, so its valid indexes are 0 through 5. The length property returns the number of elements:
const marks: number[] = [58, 68, 74, 88, 64, 90];
console.log(marks.length); // 6
console.log(marks[marks.length - 1]); // 90
console.log(marks.at(-1)); // 90 in supported runtimes
Ordinary indexed access beyond the array bounds returns undefined at runtime. Projects that enable noUncheckedIndexedAccess also see that possibility in the inferred indexed-access type.
Add, Update, and Remove TypeScript Array Elements
Assign a value to an existing index to replace that element. The assigned value must be compatible with the array’s element type.
example.ts
var marks:number[] = [58, 68, 74, 88, 64, 90]
marks[0] = 65
marks[1] = 68
marks[2] = 73
marks[3] = 74
console.log(marks[0])
console.log(marks[1])
console.log(marks[2])
console.log(marks[3])
Output
65
68
73
74
Use push() and pop() at the end of an array. Use unshift() and shift() at the beginning. Each of these operations mutates the original array.
const tasks: string[] = ["Design", "Develop"];
tasks.push("Test"); // Add at the end
tasks.unshift("Plan"); // Add at the beginning
const lastTask = tasks.pop();
const firstTask = tasks.shift();
console.log(tasks);
console.log(firstTask, lastTask);
[ 'Design', 'Develop' ]
Plan Test
Use splice() when elements must be inserted or removed at a particular index. It changes the source array and returns the removed elements.
const subjects: string[] = ["Maths", "Physics", "Biology"];
const removed = subjects.splice(1, 1, "Chemistry");
console.log(subjects);
console.log(removed);
[ 'Maths', 'Chemistry', 'Biology' ]
[ 'Physics' ]
Define a TypeScript Array of Objects
An object array can use an inline object type, an interface, or a type alias. A named type is convenient when the same object structure is used in several places.
interface Student {
id: number;
name: string;
active: boolean;
}
const students: Student[] = [
{ id: 1, name: "Anisha", active: true },
{ id: 2, name: "Roshan", active: false }
];
const activeStudents = students.filter((student) => student.active);
console.log(activeStudents);
TypeScript checks every object literal against Student. A missing required property or a property with an incompatible value produces a compile-time error.
Copy a TypeScript Array Without Sharing the Container
Assigning an array to another variable does not copy it. Both variables refer to the same array. Use spread syntax, slice(), or Array.from() to create a shallow copy.
const original: number[] = [10, 20, 30];
const spreadCopy = [...original];
const sliceCopy = original.slice();
const fromCopy = Array.from(original);
spreadCopy[0] = 99;
console.log(original);
console.log(spreadCopy);
[ 10, 20, 30 ]
[ 99, 20, 30 ]
These techniques copy the array container only. Nested objects remain shared references. When independent nested values are required, create new nested objects as well or use an appropriate structured-cloning strategy.
Create Multidimensional and Tuple Arrays
A multidimensional array is an array whose elements are arrays. Add one pair of brackets for each dimension.
const matrix: number[][] = [
[1, 2, 3],
[4, 5, 6]
];
console.log(matrix[1][2]);
6
An array type describes a variable-length collection of one element type. A tuple instead describes a fixed sequence of element types and is useful when positions have distinct meanings.
const coordinate: [number, number] = [17.385, 78.4867];
const result: [string, boolean] = ["saved", true];
TypeScript Array Methods for Searching, Transforming, and Combining Values
TypeScript exposes the standard JavaScript array methods with type information. Some methods mutate the source array, while others return a new value or a new array.
| Method | Purpose | Mutates source array? |
|---|---|---|
push(), pop() | Add or remove an element at the end | Yes |
shift(), unshift() | Remove or add an element at the beginning | Yes |
splice() | Insert, replace, or remove elements by index | Yes |
concat() | Combine arrays or values | No |
slice() | Return a selected shallow copy | No |
map() | Transform every element into a new array | No |
filter() | Return elements that satisfy a condition | No |
find() | Return the first matching element | No |
some(), every() | Test one or all elements | No |
forEach() | Run a callback for each element | No, unless the callback changes referenced values |
reduce() | Combine elements into one accumulated result | No |
sort(), reverse() | Reorder elements | Yes |
Combine TypeScript Arrays with concat()
concat() returns a new array containing the source elements followed by the supplied values or array elements. It does not modify the original arrays.
example.ts
var marks1:number[] = [58, 68, 74, 88, 64, 90]
var marks2:number[] = [82, 67]
var marks:number[] = marks1.concat(marks2)
console.log(marks)
Output
marks : 58, 68, 74, 88, 64, 90, 82, 67
A JavaScript console normally displays the resulting value as an array, although the exact console formatting depends on the runtime.
Test All TypeScript Array Elements with every()
every() calls a predicate for array elements and returns true only when the predicate succeeds for every tested element. It stops as soon as a predicate call returns a falsy value.
example.ts
var marks:number[] = [58, 68, 74, 88, 64, 90]
function isPassed(element, index, array) {
return (element >= 35)
}
var passed = marks.every(isPassed)
if(passed)
console.log("The student has passed.")
else
console.log("The student has failed")
Output
The student has passed.
The callback parameters can be typed explicitly when needed: (element: number, index: number, array: number[]) => boolean.
Iterate Through a TypeScript Array with forEach()
forEach() invokes a callback once for each array element. It is intended for side effects such as logging or updating external state. It always returns undefined; it does not collect callback return values into a new array.
example.ts
var marks:number[] = [58, 68, 26, 88, 27, 90]
function isPassed(value) {
if(value >= 35) return true
else return false
}
var passA = marks.forEach(isPassed)
console.log(passA)
Output
passA : true, true, false, true, false, true
In the example above, the callback returns booleans, but forEach() discards them. Consequently, passA is undefined. Use map() to create the intended boolean array:
const marks: number[] = [58, 68, 26, 88, 27, 90];
const passStatus: boolean[] = marks.map((mark) => mark >= 35);
console.log(passStatus);
[ true, true, false, true, false, true ]
Transform and Filter TypeScript Arrays
map() creates one transformed result for each source element. filter() creates an array containing only the elements that pass its test.
const prices: number[] = [120, 250, 80];
const pricesWithTax = prices.map((price) => price * 1.05);
const highValuePrices = prices.filter((price) => price >= 100);
console.log(pricesWithTax);
console.log(highValuePrices);
[ 126, 262.5, 84 ]
[ 120, 250 ]
Find Values in a TypeScript Array
Use includes() to test whether a value exists, indexOf() to obtain its position, and find() to return the first element satisfying a predicate. A find() result may be undefined.
const values: number[] = [12, 25, 31, 48];
console.log(values.includes(25));
console.log(values.indexOf(31));
const firstEven: number | undefined = values.find((value) => value % 2 === 0);
console.log(firstEven);
true
2
12
Calculate One Result with reduce()
reduce() processes the elements with an accumulator. Supplying an initial value makes the accumulator type and empty-array behavior clearer.
const marks: number[] = [58, 68, 74];
const total = marks.reduce((sum, mark) => sum + mark, 0);
console.log(total);
200
Sort Number and String Arrays Correctly
sort() mutates an array and compares string representations by default. Provide a comparison function for numeric ordering. Copy the array first when the original order must be preserved.
const values: number[] = [20, 3, 100];
const ascending = [...values].sort((a, b) => a - b);
const descending = [...values].sort((a, b) => b - a);
console.log(ascending);
console.log(descending);
console.log(values);
[ 3, 20, 100 ]
[ 100, 20, 3 ]
[ 20, 3, 100 ]
Use readonly TypeScript Arrays When Mutation Is Not Allowed
A readonly array permits reading and non-mutating operations but prevents changes through that reference. It can be written as readonly T[] or ReadonlyArray<T>.
const roles: readonly string[] = ["Admin", "Editor"];
console.log(roles[0]);
// roles.push("Viewer"); // Type error
// roles[0] = "Owner"; // Type error
const and readonly provide different protections. const prevents reassignment of the variable, but a normal array stored in that variable can still be mutated. A readonly array type prevents mutation through the typed reference.
Common TypeScript Array Errors
- Using a scalar annotation:
let names: stringdeclares one string, not an array. Usestring[]. - Using
int: TypeScript usesnumberunless a custominttype has been defined. - Expecting forEach() to return an array: use
map()when callback results must be collected. - Reading an invalid index: JavaScript returns
undefinedrather than automatically reporting an index error. - Sorting numbers without a comparator: pass
(a, b) => a - bfor ascending numeric order. - Accidentally sharing an array: assignment copies the reference; spread syntax or
slice()creates a shallow copy. - Assuming const makes an array immutable: use a readonly array type when callers must not mutate it.
TypeScript Array FAQs
What is the difference between T[] and Array<T>?
Both describe arrays whose elements have type T. For example, string[] and Array<string> are equivalent for ordinary use. The bracket form is compact, while the generic form can be easier to read in some nested generic types.
How do I create a TypeScript array of objects?
Define the object structure with an interface or type alias and add brackets to its name, such as const users: User[] = [...]. TypeScript will check each array element against that structure.
How do I copy a TypeScript array?
Use [...source], source.slice(), or Array.from(source) for a shallow copy. Nested objects are still shared, so copy those objects separately when independent nested data is required.
Can a TypeScript array contain more than one type?
Yes. Use a union element type such as Array<string | number>. If each position has a specific meaning and type, a tuple such as [string, number] is usually more precise.
What happens when a TypeScript array index does not exist?
The generated JavaScript returns undefined. Enable noUncheckedIndexedAccess when indexed reads should include undefined in their TypeScript types, and check the value before using it.
TypeScript Array Tutorial QA Checklist
- Confirm every declared array uses a valid element type such as
number[]rather thanint. - Check that examples distinguish zero-based indexes from the array’s
length. - Verify that mutating methods and non-mutating methods are described accurately.
- Confirm
forEach()examples do not claim that it returns collected callback values. - Check numeric
sort()examples for an explicit comparison function. - Confirm array-copy guidance identifies spread,
slice(), andArray.from()as shallow-copy operations. - Verify that a possible
undefinedresult fromfind()or invalid indexed access is handled where necessary. - Compile new examples with the intended TypeScript configuration and run them in a compatible JavaScript environment.
TypeScript Array Summary
TypeScript arrays combine JavaScript’s ordered array operations with compile-time element types. Declare arrays with T[] or Array<T>, access elements by zero-based index, and select methods according to whether the original array should be mutated. Interfaces provide reusable types for arrays of objects, tuples model fixed positional data, and readonly array types prevent mutation through a reference. Continue with the main TypeScript Tutorial for related TypeScript concepts.
TutorialKart.com