You write a typed event bus, route definition, or validation schema, and TypeScript widens your string literals to string the second you pass them into a generic helper. The downstream autocompletion dies, leaving you with useless string hints and runtime errors that the compiler should have caught.
Most developers try to patch this by adding manual type arguments at the call site or by chaining four nested utility types with conditional infer blocks. You do not need to do that anymore. Modern TypeScript versions handle literal preservation directly at the parameter boundary.
The problem: literal widening in generic configs
Here is the pattern that breaks. You want a function that defines route handlers, event tables, or API endpoints. You write a helper to infer the shape, but passing an inline object argument widens every key and primitive property.
typescripttype RouteConfig<TPath extends string> = {
path: TPath;
roles: string[];
};
function defineRoutes<TPath extends string>(
routes: RouteConfig<TPath>[]
): Record<TPath, RouteConfig<TPath>> {
const map = {} as Record<TPath, RouteConfig<TPath>>;
for (const route of routes) {
map[route.path] = route;
}
return map;
}
const config = defineRoutes([
{ path: "/users", roles: ["admin"] },
{ path: "/posts", roles: ["viewer"] },
]);
// Hovering config shows:
// const config: Record<string, RouteConfig<string>>
Because TypeScript defaults to type widening for object literals, TPath resolves to string. When you try to access a specific route later, the compiler does not protect you from typos:
textconst userRoute = config["/usrs"]; // No compiler error, returns RouteConfig<string> | undefined at runtime
The old workaround was forcing callers to write as const on every object argument:
typescriptconst config = defineRoutes([
{ path: "/users", roles: ["admin"] },
{ path: "/posts", roles: ["viewer"] },
] as const);
This often failed anyway unless your function signature had a readonly modifier on the array, triggering an immediate type error:
textThe type 'readonly [{ readonly path: "/users"; ... }]' is 'readonly' and cannot be assigned to the mutable type 'RouteConfig<string>[]'.
The clean fix: const type parameters
TypeScript 5.0 introduced the const modifier for type parameters. It tells the compiler to infer the narrowest possible literal types at the call site without requiring callers to append as const.
You add const directly before the generic type parameter name:
typescripttype Route<TPath extends string> = {
readonly path: TPath;
readonly roles: readonly string[];
};
function createRouter<const T extends readonly Route<string>[]>(
routes: T
) {
type RouteMap = {
[R in T[number] as R["path"]]: R;
};
const map = {} as RouteMap;
for (const route of routes) {
(map as any)[route.path] = route;
}
return map;
}
Now call it with a standard inline array:
typescriptconst router = createRouter([
{ path: "/admin/dashboard", roles: ["admin"] },
{ path: "/public/login", roles: ["guest"] },
]);
// Hovering router shows:
// const router: {
// "/admin/dashboard": { readonly path: "/admin/dashboard"; readonly roles: readonly ["admin"] };
// "/public/login": { readonly path: "/public/login"; readonly roles: readonly ["guest"] };
// }
If you try to read an invalid key, the compiler stops you:
typescriptconst bad = router["/admin/dashbord"];
textProperty '/admin/dashbord' does not exist on type '{ "/admin/dashboard": ...; "/public/login": ...; }'.
You do not need an as const assertion on the argument. The inference stays narrow down to the array element properties.
Pairing const parameters with simple utility types
Developers often write complex recursive conditional types to strip properties, pull keys, or build lookup tables. In most day-to-day codebases, you only need three core utility patterns to transform your narrow literal objects without breaking readability.
1. Key mapping with template literal filtering
Suppose you want to extract only the paths that start with /admin from the router without rewriting the router’s input:
typescripttype AdminPaths<T> = T extends { [K in keyof T]: any }
? keyof T & `/admin/${string}`
: never;
type AdminOnly = AdminPaths<typeof router>;
// Result: "/admin/dashboard"
2. Extracting discriminated unions without boilerplate
If you need to convert an inferred tuple of objects into a union type where one field determines the rest, use indexed access directly over the array generic:
typescripttype EventDefinition = {
readonly event: string;
readonly payload: unknown;
};
function defineEvents<const T extends readonly EventDefinition[]>(events: T) {
return {
events,
emit<E extends T[number]["event"]>(
event: E,
payload: Extract<T[number], { readonly event: E }>["payload"]
) {
// implementation
},
};
}
const bus = defineEvents([
{ event: "USER_LOGGED_IN", payload: { userId: "string", timestamp: 123 } },
{ event: "SESSION_EXPIRED", payload: { reason: "timeout" } },
]);
// Autocompletes "USER_LOGGED_IN" | "SESSION_EXPIRED"
bus.emit("USER_LOGGED_IN", { userId: "100", timestamp: Date.now() });
// Fails: payload does not match the specific event
bus.emit("SESSION_EXPIRED", { userId: "100" });
The error is precise:
textType '{ userId: string; }' is not assignable to type '{ reason: string; }'.
Object literal may only specify known properties, and 'userId' does not exist in type '{ reason: string; }'.
Notice how Extract<T[number], { readonly event: E }> replaces a multi-line conditional type. T[number] creates the union of all elements in the tuple. Extract<Union, Filter> handles the discriminator match.
Edge case 1: Passing pre-declared variables breaks inference
The const modifier applies only to expressions created directly at the call site. If an object or array is declared outside the function call without its own type annotations, it widens before your generic function ever sees it.
typescriptconst routesList = [
{ path: "/health", roles: ["system"] },
];
const healthRouter = createRouter(routesList);
// Inferred type: { [x: string]: { readonly path: string; readonly roles: readonly string[]; } }
Why this happens: routesList is evaluated at its own declaration. TypeScript sees a mutable array and gives it the type { path: string; roles: string[] }[]. When you pass it to createRouter, the const modifier receives a type that is already wide. It cannot look back through the AST to find the original literal values.
If you must define the value separately, you have to use as const at the variable declaration site:
typescriptconst routesList = [
{ path: "/health", roles: ["system"] },
] as const;
const healthRouter = createRouter(routesList);
// Correctly infers "/health"
Keep your call sites direct when using const type parameters to avoid this friction.
Edge case 2: Readonly mutations inside the generic function
When const is applied to a type parameter, TypeScript infers everything inside as readonly. Arrays become readonly T[], and object properties become readonly.
If your function body attempts to mutate, slice, or sort the incoming data using mutable array methods, the compiler rejects the implementation:
typescriptfunction registerEndpoints<const T extends readonly string[]>(endpoints: T) {
// Error: Property 'push' does not exist on type 'T'.
endpoints.push("/default");
// Error: Property 'sort' does not exist on type 'T'.
endpoints.sort();
}
To work with the input data internally while preserving narrow types for the caller:
- Clone mutable arrays inside your implementation using the spread operator:
[...endpoints].sort(). - Do not mark return types with manual mutable types if you are passing the data back out; let the return type mirror the caller’s readonly inference.
typescriptfunction registerEndpoints<const T extends readonly string[]>(endpoints: T) {
const mutableEndpoints = [...endpoints];
mutableEndpoints.sort();
return mutableEndpoints;
}
Verifying your inference works
You can test whether your literal inference remains narrow using the built-in TypeScript utility type assertType pattern without any external dependencies.
Create a verification block in your test file:
typescripttype Expect<T extends true> = T;
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2
? true
: false;
const routes = createRouter([
{ path: "/api/v1", roles: ["user"] },
{ path: "/api/v2", roles: ["admin"] },
]);
type Cases = [
// If this line compiles, the keys are exact literals, not string
Expect<Equal<keyof typeof routes, "/api/v1" | "/api/v2">>,
// This will fail to compile if roles widened to string[]
Expect<Equal<(typeof routes)["/api/v1"]["roles"], readonly ["user"]>>
];
Run tsc --noEmit on your project. If the inference widened anywhere, the type assertion above produces a compile-time error:
textType 'false' does not satisfy the constraint 'true'.
If it exits with status code 0, your literal types are preserved through the generic boundary. Always run this verification step in your test pipeline to catch regressions early when refactoring shared type definitions.