Skip to the solution
HardFrontend9 min read

What are template literal types?

573 views

The problem

Question presented to candidate: "What are template literal types in TypeScript? Show me a couple of places you would actually use them, and how you would pull information back out of a string type."

What a strong answer should cover:

  • The syntax mirrors JavaScript template strings, but builds string literal types: `on${Capitalize<Ev>}`; added in TypeScript 4.1
  • Unions in the holes multiply: every combination is produced, and very large products are refused (error TS2590)
  • The intrinsic helpers Uppercase, Lowercase, Capitalize, Uncapitalize, and primitive holes such as `${number}px` that make patterns rather than finite unions
  • Combined with key remapping (as) to derive property names, e.g. onNameChange handlers from a model
  • With infer in a conditional type they parse strings: route params, Split, dotted paths; a leading infer takes the shortest match

Code / implementation expected: Yes β€” derive event or handler names, and write one small parser such as route params.

  • template-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 Β· 9 sections

Run the code

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

TypeScriptBuilding string types: unions, intrinsics, patterns and handler names
TypeScriptParsing strings: route params, Split, dotted paths and limits

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 73 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 nextHard

How do you author library types that pass `isolatedDeclarations` for `oxc` / `tsdown` builds?

Continue