Type-safe naming conventions
Derive identifiers, event names, or locale keys from existing string unions.
TypeScript · Function
Template literal types build string-literal types from fixed text and interpolated types. Unions in placeholders expand into every permitted combination, enabling type-safe naming patterns and inferred string structure.
Template literal types use backtick syntax in type positions to construct string-literal types. Concrete substitutions concatenate directly; union substitutions generate every permitted combination, which can then constrain names, keys, and API strings.
type Name = `prefix${Type}suffix`;type Locale = "welcome_email" | "email_heading";
type Section = "footer_title" | "footer_sendoff";
type LocaleID = `${Locale | Section}_id`;
const id: LocaleID = "welcome_email_id";
// const invalid: LocaleID = "header_id"; // Type errorThe interpolated unions are combined into the permitted string-literal union.
Derive identifiers, event names, or locale keys from existing string unions.
Tie an attribute literal to the matching callback argument type.
Transform object keys into patterned API methods with mapped types.
A template literal type is a string-literal type written with backticks in a type position. With concrete literal substitutions it concatenates text, while union substitutions expand into the set of all combinations.
Follow-up: How are multiple interpolated unions combined? Each member of one union is combined with each member of the other, producing a cross-product.
Template literal types can derive names from existing string unions, such as adding an _id suffix to locale identifiers. This preserves a finite set of valid strings and rejects values outside that derived union.
Follow-up: How would you derive event names from object keys? Use keyof to obtain the keys, constrain them to strings when necessary, and interpolate them into the desired pattern.
They can infer substrings with infer when a generic string matches a template pattern. A common design captures a literal argument, validates it against an allowed union, and uses indexed access to connect that argument to related callback data.
Follow-up: What limitation should guide this design? For very large string unions, prefer ahead-of-time generation to avoid excessive type complexity.
String literal typesUnion typesMapped typesIndexed access typesConditional typesIntrinsic string manipulation types