I Stopped Asking Callers for `as const`. Const Type Parameters Do It.
A teammate's PR adds a new event to the bus your defineEvents() helper manages. It compiles clean. No red squiggle, no CI failure, no review comment. Three weeks later someone adds a switch over those event names, forgets a case, and TypeScript says nothing about it either — because by the time it reaches that switch, the type isn't 'login' | 'logout' | 'refresh' anymore. It's just string . It's…
A colleague's pull request introduced a new event to the 'defineEvents()' helper they created, which managed a bus. At first glance, everything seemed fine: the code compiled without issues, no CI failures, and no review comments. However, three weeks later, someone added a switch over the event names and forgot to include a case, causing TypeScript to report no errors.
The issue arose because the type had changed from 'login' | 'logout' | 'refresh' to just 'string'. The original failure had occurred earlier when a similar issue was encountered within a reducer's file, and using 'as const' had resolved it. This time, the problem was different – it affected everyone who used the helper, not just the code author.
The helper function, 'defineEvents', took an array of string literals as its parameter and returned an object with the names array and an 'on' method to handle events. When the event names were passed as an array literal, TypeScript widened the type to 'string[]', which led to compiler errors when a typo was introduced in a switch statement.
The solution was to use the 'const' type modifier on the function's signature. By declaring the type parameter 'T' as 'const', TypeScript would infer the type as a 'readonly tuple' instead of a mutable array, preserving the literal string values. This change allowed the compiler to catch errors, like missing cases in the switch statement, without requiring a 'as const' suffix on every call site.
The 'const' modifier provided a more effective way to ensure type safety, making the helper more reliable for developers who might forget important details.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to