Nameof Keyword
1 min readRapid overview
Avoiding String Literals in JavaScript/TypeScript
JavaScript doesn’t have a nameof keyword. Use constants or keyof to keep names in sync.
Constants
const Handlers = {
createOrder: 'createOrder',
cancelOrder: 'cancelOrder'
} as const;
type HandlerName = keyof typeof Handlers;
keyof for safe property names
type User = { id: string; name: string };
const field: keyof User = 'name';
Interview prompt
- How do you avoid magic strings in a large codebase?