Today, we will discuss an interesting topic in TypeScript. In this tutorial, I will explain how to clear a typed array in TypeScript while preserving its original type.
Clear an Array in TypeScript While Preserving Its Type
Let’s say we have an array of a custom type called Person in our TypeScript code:
type Person = {
name: string;
age: number;
};
const people: Person[] = [
{ name: "John Smith", age: 35 },
{ name: "Emily Johnson", age: 28 },
{ name: "Michael Davis", age: 42 },
];
Now, suppose we want to clear the people array at some point in our code. The most straightforward way would be to simply assign an empty array to it:
people = [];
However, this does not work here. people is declared with const, so TypeScript refuses the assignment with error TS2588. If you declare it with let, the assignment compiles and people keeps its Person[] type, but it now points to a new empty array: any other variable or object that still references the old array keeps all the old items.
const array is a compile-time error.Check out Find the Length of an Array in TypeScript
The Solution
To clear the array while preserving its type, we can use the splice() method. The splice() method allows us to modify an array by removing or replacing existing elements and/or adding new elements.
Here’s how we can use splice() to clear the people array:
people.splice(0, people.length);
In this code, we call splice() on the people array. The first argument, 0, specifies the starting index from where we want to start modifying the array. The second argument, people.length, indicates the number of elements we want to remove. By passing people.length, we ensure that all elements from index 0 to the end of the array are removed.
After executing this line, the people array will be empty, but it will still retain its original type of Person[].
Here is a complete example you can run. It also shows that every reference to the array sees it cleared, and that the array still only accepts Person objects:
type Person = {
name: string;
age: number;
};
const people: Person[] = [
{ name: "John Smith", age: 35 },
{ name: "Emily Johnson", age: 28 },
{ name: "Michael Davis", age: 42 },
];
const sameArray = people; // another reference to the same array
people.splice(0, people.length);
console.log(people.length); // 0
console.log(sameArray.length); // 0: every reference sees the cleared array
people.push({ name: "Anna Lee", age: 31 }); // still a Person[]: only Person objects are allowed
console.log(people);
Output:
0
0
[ { name: 'Anna Lee', age: 31 } ]
splice(0, people.length) empties the same array in place.Read Remove an Item from an Array in TypeScript
Advantages of Using TypeScript splice() method
Using the splice() method in TypeScript has several advantages:
- Type Preservation: As mentioned earlier, using
splice()allows us to clear the array while preserving its original type. This is crucial in TypeScript, where type safety is a key feature. - In-Place Modification:
splice()modifies the array in-place, which means it directly changes the original array. This can be more efficient than creating a new empty array and assigning it to the variable. - Flexibility:
splice()is a versatile method that allows you to remove, replace, or add elements to an array. In our case, we use it to remove all elements, but it can be used for other array manipulation tasks as well.
Example
Now, let me show you a real example.
Suppose we are building a web application for a U.S.-based company that manages employee records. We have an array of Employee objects:
type Employee = {
id: number;
name: string;
department: string;
};
const employees: Employee[] = [
{ id: 1, name: "Sarah Thompson", department: "Marketing" },
{ id: 2, name: "David Wilson", department: "Engineering" },
{ id: 3, name: "Emily Roberts", department: "Sales" },
];
At some point in our application, we need to clear the employees array, perhaps after performing a certain operation or when the user logs out. We can use the splice() method to achieve this:
employees.splice(0, employees.length);
By doing so, we clear the employees array while preserving its Employee[] type. This ensures that our code remains type-safe and maintainable.
Conclusion
Clearing a typed array in TypeScript while preserving its type is sometimes very useful in many projects. By using the splice() method, we can achieve this easily and efficiently. The splice() method allows us to modify the array in-place, remove all elements, and retain the original type information.
In this tutorial, I explained how to clear an array in TypeScript while preserving Its Type.
You may also like:
Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn