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.tsfile in theconstantsfolder for simplicity. - Use explicit type annotations for structured or domain-specific constants.
- Write descriptive names that clarify intent and usage.
- Use
export constto prevent rebinding. It does not make objects or arrays immutable. - Use
UPPER_SNAKE_CASEfor all constant names. - Include unit suffixes in names when applicable (e.g.,
_PX,_MS,_CHARS) to clarify what the value represents. - Use
Readonly<Type>oras constfor object and array constants so TypeScript rejects accidental writes. Both are compile-time only, andReadonly<Type>is shallow; copy the value before changing it. - For a fixed set of values, derive the union type from an
as constobject, and type lookup maps withsatisfies(see Derive types from constant objects and Type constant maps).