#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
extendsandinfer. - 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
- Create a type
Events = "click" | "hover". - Create a type
OnEventsthat adds βonβ to the start:"onclick" | "onhover". - Use Capitalize to make it camelCase:
"onClick" | "onHover".
See you in Phase 5!