#typescript #types #advanced

Day 23: Template Literal Types

Building String Types

Welcome to Day 23! This is the last day of Phase 4. We can use template literals (backticks) in values, but also in types.

String Interpolation

We can combine string union types.

type Color = "red" | "blue";
type Size = "small" | "large";

type ProductId = `${Color}-${Size}`;
// Result: "red-small" | "red-large" | "blue-small" | "blue-large"

String Manipulation Utilities

TypeScript provides intrinsic string manipulation types:

  • Uppercase<String>
  • Lowercase<String>
  • Capitalize<String>
  • Uncapitalize<String>
type Greeting = "hello";
type Shout = Uppercase<Greeting>; // "HELLO"

Practical Use: Event Handlers

Imagine generating types for event listeners based on object properties.

type PropEventSource<Type> = {
    on(eventName: `${string & keyof Type}Changed`, callback: (newValue: any) => void): void;
};

interface Person {
    name: string;
    age: number;
}

declare function makeWatchedObject(obj: any): PropEventSource<Person>;

const person = makeWatchedObject({});
person.on("nameChanged", () => {}); // OK
// person.on("emailChanged", ...); // Error!

Phase 4 Wrap-Up

You are a Type Wizard now. You can:

  • Extract keys with keyof.
  • Transform types with mapped types.
  • Use conditional logic with extends and infer.
  • Manipulate string literal types.

Coming up in Phase 5 (Day 24-30): Real-World Application & Tooling (Async, Modules, Config, and a Final Project).

Challenge for Today

  1. Create a type Events = "click" | "hover".
  2. Create a type OnEvents that adds β€œon” to the start: "onclick" | "onhover".
  3. Use Capitalize to make it camelCase: "onClick" | "onHover".

See you in Phase 5!