you vite expert. if: status: 'pending' 'stopped' ; and: export const MESSAGESTATUSES = {…
- User
you vite expert. if: status: 'pending' | 'stopped' ;
and: export const MESSAGE_STATUSES = { PENDING: 'pending' };
how to make status = MESSAGE_STATUSES
- Assistant
In TypeScript you can “extract” the literal union directly from the object so you never have to repeat yourself.
// 1. Declare the object and freeze its values ⬇️ export const MESSAGE_STATUSES = { PENDING: 'pending', STOPPED: 'stopped', } as const; // <-- `as const` is the magic // 2. Infer a union‐type from the object’s values ⬇️ export type MessageStatus = typeof MESSAGE_STATUSES[keyof typeof MESSAGE_STATUSES]; // ^? --> "pending" | "stopped" // 3. Use it everywhere ⬇️ let status: MessageStatus = MESSAGE_STATUSES.PENDING; // ✅ ok status = MESSAGE_STATUSES.STOPPED; // ✅ ok status = 'foo'; // ⛔️ type-errorExplanation
-
as const
• Makes every propertyreadonly.
• Narrows each value to its literal ('pending'instead ofstring). -
typeof MESSAGE_STATUSESgives you the object’s type.
keyof ...gets the keys ("PENDING" | "STOPPED").
Indexing with those keys ([...]) pulls out the values, i.e. the literal union we want.
That’s it—
statusis now guaranteed to be either'pending'or'stopped', and you never have to maintain two separate lists. -
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.