DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk2 min

How to Clear an Array in TypeScript Without Changing Its Type

Set a mutable array’s length to zero to clear its contents in place. Its declared TypeScript element type remains unchanged.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To empty a mutable TypeScript array without changing its declared element type, set arr.length = 0. This clears the existing array object in place; the variable remains, for example, a string[], ready to accept strings again.

Clear a mutable array in place

Assigning zero to an ordinary JavaScript array’s writable length removes its elements. TypeScript’s annotation describes the array’s static element type, not how many items it currently contains.

const names: string[] = ["Ada", "Grace"];
names.length = 0;

names.push("Linus"); // accepted: names is still string[]

The binding declared with const cannot be reassigned, but its array contents can still be mutated. The JavaScript behavior is documented in MDN’s Array.length reference; TypeScript’s Handbook discussion of object and array types explains the static typing.

Choose between clearing and replacing

Goal Operation Effect
Empty the existing array object arr.length = 0 Mutates the same array; its length becomes zero.
Remove elements using an array method arr.splice(0, arr.length) Removes the selected elements from the original array in place.
Use a different empty array arr = [] (when the binding is mutable) Replaces the binding’s value; references to the old array still point to that old array.

splice() is an alternative when you want to express removal through an array method:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const names: string[] = ["Ada", "Grace"];
names.splice(0, names.length);

MDN documents splice() as a mutating operation in its Array.prototype.splice() reference. Use either in-place operation when other code should continue to observe the same array object.

Readonly references cannot be cleared through that type

TypeScript’s readonly T[] and ReadonlyArray<T> types prevent mutation through that reference. Setting length or calling splice() on it is a type error because those operations mutate the array.

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem
function clear(values: string[]): void {
  values.length = 0;
}

function cannotClear(values: readonly string[]): void {
  // values.length = 0; // TypeScript error
  // values.splice(0);  // TypeScript error
}

If clearing is part of a function’s job, give it a mutable array parameter, such as string[]. A type assertion can silence a static restriction, but it does not change the runtime object or make a frozen object mutable. TypeScript’s type assertions documentation describes assertions as a compile-time aid, not a runtime conversion.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Do not use a fixed tuple for a collection you empty

A tuple such as [string, number] expresses fixed positions and element types. Clearing it at runtime does not change its declared type into []; TypeScript may still treat the value according to the tuple’s positional declaration. If emptying is a normal operation, use a general mutable array type instead, such as (string | number)[].

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

TypeScript documents tuple and readonly tuple behavior in its 3.4 release notes and its Handbook array discussion.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.