Skip to content
TypeScript

const Assertions

Narrow types using as const.

By EZ4Code Team
constassertion

Code

// Array becomes readonly tuple
const arr = [1, 2, 3] as const;
// type: readonly [1, 2, 3]

// Object properties become readonly literals
const config = {
  endpoint: "/api",
  methods: ["GET", "POST"]
} as const;
// { readonly endpoint: "/api"; readonly methods: readonly ["GET", "POST"] }

// String becomes literal type
const color = "red" as const;  // "red"

// Used to derive union type
const STATUSES = ["pending", "done", "error"] as const;
type Status = typeof STATUSES[number]; // "pending" | "done" | "error"

Explanation

as const makes TS infer the narrowest literal types.

More TypeScript Snippets