AI Hints
Home›TypeScript Tutorial›Template Types and Practice
TypeScript · Lesson 70 of 120

Template Literal Types

Types from strings.

⏱ 2 min read▶ Video at 53:26🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Template literal types build string types from other types, with the same backtick syntax as template strings. They can describe event names, ID formats, and CSS values.

Template Literal Types
From the video: Template Literal Types
  • Backticks for types
  • Build string types
  • Names and formats

Event names

Entity is bike or order. Action is created or deleted. The event type combines them into four exact names. A real name is fine. A typo is rejected. Run it.

app.tstypescript
type Entity = "bike" | "order";
type Action = "created" | "deleted";
type EventName = `${Entity}.${Action}`;

const ok: EventName = "order.created";
const typo: EventName = "order.updated";
Output
app.ts line 6: Type '"order.updated"' is not assignable to type '"bike.created" | "bike.deleted" | "order.created" | "order.deleted"'.

More examples

An order reference can be NW dash, then a number. ACSS size can be a number, then PX. And with keyof, you can build names like get model, from property names.

keyvalue
Order ref`NW-${number}`
CSS`${number}px`
Getters`get${Capitalize<K>}`
Resultexact string types

Summary

Template literal types describe exact string patterns. Next, practice with utility types.

Key takeaways
  • `${A}.${B}`
  • Exact names
  • Typos caught
Next up: Practice: Utility Types — an update form