Skip to content

Constants

bookmarks is a made-up module: the examples show the pattern, not existing code.

Example: a default value and limits

import type { BookmarkDraft } from "@/src/bookmarks/types";

export const EMPTY_BOOKMARK_DRAFT: Readonly<BookmarkDraft> = {
  title: "",
  url: "",
};

export const BOOKMARK_TITLE_MAX_LENGTH_CHARS = 255;
export const BOOKMARK_SEARCH_DEBOUNCE_MS = 300;

Usage

import { EMPTY_BOOKMARK_DRAFT } from "@/src/bookmarks/constants";

const draft = ref<BookmarkDraft>({ ...EMPTY_BOOKMARK_DRAFT });

Copy the shared constant into a new object before changing it. Readonly<BookmarkDraft> makes TypeScript reject direct writes such as EMPTY_BOOKMARK_DRAFT.title = "...", but it does not freeze the object at runtime (see Understand const and readonly).

Best practices

  • Group constants by purpose into logically named files (e.g., constants/ui.ts, constants/messages.ts).
  • If a module has only a few constants (1-4), it is allowed to use an index.ts file in the constants folder for simplicity.
  • Use explicit type annotations for structured or domain-specific constants.
  • Write descriptive names that clarify intent and usage.
  • Use export const to prevent rebinding. It does not make objects or arrays immutable.
  • Use UPPER_SNAKE_CASE for all constant names.
  • Include unit suffixes in names when applicable (e.g., _PX, _MS, _CHARS) to clarify what the value represents.
  • Use Readonly<Type> or as const for object and array constants so TypeScript rejects accidental writes. Both are compile-time only, and Readonly<Type> is shallow; copy the value before changing it.
  • For a fixed set of values, derive the union type from an as const object, and type lookup maps with satisfies (see Derive types from constant objects and Type constant maps).