How does 'as const' interact with function calls, and why can't you apply it directly to a function's return expression the way you can to a variable's literal value?
Short answer
'as const' only works on literal EXPRESSIONS (object/array/primitive literals) written directly at that position — it can't retroactively make a value that's ALREADY been computed by a function call more specific, since the assertion needs to see the actual literal syntax to…
Advertisement
AModel answer
'as const' only works on literal EXPRESSIONS (object/array/primitive literals) written directly at that position — it can't retroactively make a value that's ALREADY been computed by a function call more specific, since the assertion needs to see the actual literal syntax to lock in literal types; wrapping the literal INSIDE the function (and letting the function's return type reflect that) is the correct approach instead.
function getConfig() {
return { theme: 'dark' } as const; // correct: applied directly to the literal being returned
}
// NOT: const result = getConfig() as const; -- this wouldn't add any extra narrowing beyond what getConfig() already returnsReal-world example
Designing factory functions whose return type should preserve literal types, by applying 'as const' at the actual literal construction site.
Likely follow-ups
- How would you type a factory function to return a precise literal-typed object without needing to manually repeat 'as const' at every call site?
Related topics