Keep defaults from widening types with NoInfer
Use TypeScript’s NoInfer to check a default against the choices in a list without letting the default widen the inferred union.
You write a helper that opens a settings page on a default tab. The page has a profile tab and a security tab, but a call with billing as the default passes type checking. The function lets that default participate in the same inference as the list.
See where the extra value enters
Both parameters mention T. The array supplies "profile" and "security" as candidates. The default supplies "billing", which TypeScript can include in the union.
function defineTabs<T extends string>(tabs: readonly T[], initial: T) {
return { tabs, initial }
}
const settings = defineTabs(["profile", "security"], "billing")
const admitted: typeof settings.initial = "billing"The assignment to admitted passes, even though the tabs array has no billing entry.
The return type shows a second cost. Code that reads settings.initial sees a union with "billing" in it. A switch that handles the two real tabs now looks incomplete to TypeScript.
Infer from the list, then check the default
In TypeScript 5.4 or later, wrap the second parameter in NoInfer<T>. TypeScript uses the list to infer T, then checks whether the default fits that type. You can leave the implementation as it is.
function defineTabs<T extends string>(tabs: readonly T[], initial: NoInfer<T>) {
return { tabs, initial }
}
defineTabs(["profile", "security"], "profile")
// @ts-expect-error: "billing" is outside the inferred union
defineTabs(["profile", "security"], "billing")
const loose = ["profile", "security"]
defineTabs(loose, "billing")
const fixed = ["profile", "security"] as const
defineTabs(fixed, "security")Remove the @ts-expect-error line and TypeScript reports that "billing" cannot be assigned to "profile" | "security".
The call with loose still passes. TypeScript inferred string[] at the variable declaration, where a mutable array could gain other strings. The helper can only infer string from that array. Use as const at the declaration for a fixed list. The readonly T[] parameter accepts that tuple without asking the caller to copy it.
An API response can still contain any string your server sends. For tabs loaded at runtime, check that the list contains the requested default before passing it to the UI.