Skip to the solution
EasyFrontend9 min read

What are literal types?

426 views

The problem

Question presented to candidate: "What is a literal type in TypeScript? Show me where you would use one, and explain why `const x = 'up'` and `let x = 'up'` end up with different types."

What a strong answer should cover:

  • A literal type is a type with exactly one value (`"up"`, `42`, `true`); a union of literals models a closed set of allowed values
  • `boolean` is just `true | false`; string, number, boolean and bigint literals all exist
  • Widening: `const` keeps the literal type, `let` and object-literal properties widen to `string` / `number`, which is the classic "string is not assignable to 'GET' | 'POST'" error
  • The fixes: annotate with the union, use `as const`, or derive the union from a const array with `(typeof ARR)[number]`
  • Comparing against a literal (`===`, `switch`) narrows the union, enabling exhaustiveness checks with `never`
  • Literal types are erased: untrusted strings still need a run-time guard

Code / implementation expected: Yes β€” a function that accepts a literal union, a widening error and its fix.

  • literal-types

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptLiteral types, literal unions and const vs let
TypeScriptObject widening, as const, deriving a union and narrowing

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 11 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

How does TypeScript handle null and undefined safely?

Continue