Capítulo 11 de 36
Template literal types use JS template-literal syntax at the type level — concatenating string literal types, expanding unions into every possible combination, and (via generic inference) deriving one part of a string type from another.
`hello ${World}` with World a string literal type produces a new, concatenated string literal type.`${string & keyof Type}Changed` constrains a parameter to exactly "one of Type's keys, with Changed appended" — catches typos and using the bare key instead of the derived event name as compile errors, instead of accepting any string.on<Key extends string & keyof Type>(eventName: \${Key}Changed`, callback: (v: Type[Key]) => void) lets TypeScript work backward from a call-site string ("firstNameChanged") to infer Key ("firstName"), then use indexed access (Type[Key]) to type the callback argument correctly per-property — turning a naive any`-typed callback into one whose parameter type tracks the specific property that changed..d.ts, for performance), operate on string literal types using the same logic as the equivalent JS runtime string methods (not locale-aware):
Uppercase<S> / Lowercase<S>: transform every character.Capitalize<S> / Uncapitalize<S>: transform only the first character.type PropEventSource<Type> = {
on<Key extends string & keyof Type>(
eventName: `${Key}Changed`,
callback: (newValue: Type[Key]) => void
): void;
};
declare function makeWatchedObject<T>(obj: T): T & PropEventSource<T>;
const person = makeWatchedObject({ firstName: "Saoirse", age: 26 });
person.on("firstNameChanged", (v) => v.toUpperCase()); // v: string
person.on("ageChanged", (v) => v < 0); // v: number
Key bound to the source object's keys.| Intrinsic type | Effect |
|---|---|
Uppercase<S> | every character → uppercase |
Lowercase<S> | every character → lowercase |
Capitalize<S> | first character → uppercase |
Uncapitalize<S> | first character → lowercase |
`${string & keyof T}Suffix` to constrain a string parameter to a derived form of an object's actual keys — it turns "typo in an event name" into a compile error instead of a silent runtime no-op.Key and indexed access (Type[Key]) whenever a callback's argument type should track which variant/property triggered it.as key-remapping clauses commonly use template literal types to derive new property names (e.g. get${Capitalize<...>}).infer: template literal patterns can also be matched and destructured via infer inside a conditional type.