Const declarations and const assertions affect inference differently. A const object can still have mutable properties with widened types.
Before you start
You should be comfortable with JavaScript values, functions and objects. Use a TypeScript project with strict checking enabled when trying the examples. Separate what the compiler proves from what must still be checked when values arrive at runtime.
The practical goal is to reason through this situation: {method: 'GET'} as const retains the literal and marks properties readonly in the inferred type. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: Inspect the inferred value
A const variable cannot be reassigned, but its object’s properties can change. The inferred property may therefore widen to string.
Step 2: Choose the required contract
If a function accepts only GET or POST, preserve that information at object creation with contextual typing or a const assertion.
Step 3: Separate typing from freezing
Readonly inference restricts typed assignments. Another JavaScript reference can still mutate the object unless runtime immutability is enforced separately.
Worked scenario
{method: 'GET'} as const retains the literal and marks properties readonly in the inferred type.
const loose = { method: 'GET' };
const precise = { method: 'GET' } as const;
function request(method: 'GET' | 'POST') { return method; }
request(precise.method);
// request(loose.method); // string is wider than this contract
loose.method = 'POST';
// precise.method = 'POST'; // readonly at compile timeConst assertions suit fixed configuration. If editing the method is a requirement, an explicit 'GET' | 'POST' property type expresses that freedom more accurately.
Common mistake
Readonly types are not runtime freezing.
Verify the behavior
Inspect both inferred property types in the editor. Try reassignment and property mutation separately; they are different restrictions.
Interview exercise
Pass a constrained method safely.
Answer and reasoning
Preserve the literal through contextual typing, an explicit annotation or const assertion; choose the least restrictive valid contract.
Continue learning
Compare the scenario with the TypeScript interview questions and test your understanding with the TypeScript MCQs. For terminology and implementation details, consult the reference material.