🔷 TypeScript Intermediate

What are template literal types in TypeScript?

Answer

Template literal types (TS 4.1) bring JavaScript template literal syntax into the type system, allowing string literal types to be combined and transformed. Basic example: type EventName<T extends string> = `on\${Capitalize<T>}`;EventName<"click"> becomes "onClick". Union distribution: type Directions = "top" | "right" | "bottom" | "left"; type CSSProp = `margin-\${Directions}`; — produces "margin-top" | "margin-right" | "margin-bottom" | "margin-left". TypeScript also provides string manipulation utility types: Uppercase<S>, Lowercase<S>, Capitalize<S>, Uncapitalize<S>. Template literal types are used for: type-safe event names, CSS property names, API endpoint paths, i18n keys, and strongly typed string manipulation. Combined with mapped types and infer, they enable extremely precise typing of string-based APIs.