October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

TypeScript Const Arrays: Keep Literal Types and Use Them Safely

Use as const to preserve an array literal’s exact values as a readonly tuple, then derive a union with typeof values[number].
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To preserve an array literal’s exact values in its TypeScript type, add as const: const directions = ["north", "south"] as const infers readonly ["north", "south"]. You can then derive the allowed-value union with type Direction = typeof directions[number]. A JavaScript const declaration by itself does not make an array’s contents readonly.

What does “const array” mean in TypeScript?

The phrase can refer to two different things. JavaScript’s const prevents reassignment of the variable binding, but it does not prevent changes to the array. TypeScript’s as const is a type assertion on a literal expression: it preserves literal values and makes an array literal a readonly tuple.

As an Amazon Associate I earn from qualifying purchases.

const mutable = ["north", "south"];
// string[]
mutable.push("east"); // allowed

const fixed = ["north", "south"] as const;
// readonly ["north", "south"]
// fixed.push("east"); // TypeScript error

TypeScript’s 3.4 release notes describe const assertions as preventing literal types from being widened; they also state that “array literals become readonly tuples.” This is a compile-time type effect, not a runtime freeze: the assertion does not restructure or freeze the value in JavaScript.

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

How do you get a union type from a const array?

Use typeof array[number] to get the union of the tuple’s element types. This is useful when a fixed list of values should also define the values accepted elsewhere in the program.

const roles = ["admin", "editor", "viewer"] as const;
type Role = typeof roles[number];
// "admin" | "editor" | "viewer"

function canEdit(role: Role) {
  return role === "admin" || role === "editor";
}

Here, typeof roles is the tuple type, and indexing it with number produces the union of its element types. The TypeScript Handbook’s object types documentation covers readonly arrays and tuples.

How do you check an array without widening its exact values?

Use satisfies when you want TypeScript to check a value against a broader contract while keeping its more specific inferred type. The operator was introduced in TypeScript 4.9.

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
const colors = ["red", "green", "blue"] as const
  satisfies readonly string[];

The expression is checked as compatible with a readonly string array, while colors retains its readonly tuple type and exact members. A normal type annotation can be simpler when the broader type is all the program needs and preserving individual entries is unnecessary.

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

The same pattern works for structured entries:

type Route = { path: `/${string}`; method: "GET" | "POST" };

const routes = [
  { path: "/users", method: "GET" },
  { path: "/users", method: "POST" },
] as const satisfies readonly Route[];

This checks that each entry meets the Route contract while retaining the literal paths and methods in the inferred type.

How can a generic function preserve inline literal values?

In TypeScript 5.0 and later, a const type parameter can request const-like inference for inline arguments. Make the constraint readonly-compatible so a readonly tuple can satisfy it.

function first<const T extends readonly unknown[]>(values: T): T[number] {
  return values[0];
}

const selected = first(["small", "large"]);
// "small" | "large"

TypeScript’s 5.0 release notes explain that a const modifier on a type parameter makes const-like inference the default. If the constraint were mutable, such as string[], a readonly tuple would not be assignable to it and inference could fall back to the wider constraint. This feature also cannot recover literal values from a variable already inferred as string[].

How should a function accept const arrays?

If a function only reads an array, declare its parameter as readonly T[] or ReadonlyArray<T>. This accepts both mutable arrays and readonly tuples:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function printAll(values: readonly string[]) {
  for (const value of values) console.log(value);
}

A readonly tuple cannot be passed to a parameter typed as a mutable array, such as string[], because that function could mutate it. If the function needs to change its input, either require mutable data or create a mutable copy before editing it.

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

Which pattern should you choose?

Need Pattern What it gives you
Fixed literal values and exact element types as const A readonly tuple that preserves each literal
A union of the fixed values typeof values[number] A union type made from the tuple’s element types
Compatibility checking without losing the specific inferred type as const satisfies Contract A checked value that retains its narrow type
A generic function that should infer from inline literals TypeScript 5.0+ const type parameter with a readonly-compatible constraint Const-like inference for inline arguments
Read-only input that may be dynamic readonly T[] or ReadonlyArray<T> A parameter that accepts mutable arrays and readonly tuples
Dynamic length or contents A normal array or readonly array type An array type without a fixed tuple shape

What are the common pitfalls?

  • const list = ["a", "b"] is still a mutable string[]; the declaration protects the binding, not the elements.
  • as const applies to a literal expression. It does not restore exact values after a dynamic array has widened to string[].
  • Readonly types prevent mutation through that TypeScript reference; they are not a runtime freeze or a security boundary.
  • A readonly tuple is not assignable to a mutable array parameter. Use a readonly parameter when the function does not need to mutate its input.
  • as const keeps a fixed tuple shape. For arrays whose length or contents vary, use an array type instead.

TypeScript’s basic types documentation explains that type assertions do not perform special runtime checking or change the runtime value.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.