They have the same syntax as template literal strings in JavaScript, but are used in type positions. When used with concrete literal types, a template literal produces a new string literal type by concatenating the contents.
When a union is used in the interpolated position, the type is the set of every possible string literal that could be represented by each union member:
typeEmailLocaleIDs = "welcome_email" | "email_heading";typeFooterLocaleIDs = "footer_title" | "footer_sendoff";
type// ^ = type AllLocaleIDs = "welcome_email_id" | "email_heading_id" | "footer_title_id" | "footer_sendoff_id"AllLocaleIDs = `${EmailLocaleIDs |FooterLocaleIDs }_id`;
For each interpolated position in the template literal, the unions are cross multiplied:
type// ^ = type LocaleMessageIDs = "en_welcome_email_id" | "en_email_heading_id" | "en_footer_title_id" | "en_footer_sendoff_id" | "ja_welcome_email_id" | "ja_email_heading_id" | "ja_footer_title_id" | "ja_footer_sendoff_id" | "pt_welcome_email_id" | "pt_email_heading_id" | "pt_footer_title_id" | "pt_footer_sendoff_id"LocaleMessageIDs = `${Lang }_${AllLocaleIDs }`;
We generally recommend that people use ahead-of-time generation for large string unions, but this is useful in smaller cases.
The power in template literals comes when defining a new string based off an existing string inside a type.
For example, a common pattern in JavaScript is to extend an object based on the fields that it currently has. We’ll provide a type definition for a function which adds support for an on
function which lets you know when a value has changed:
constperson =makeWatchedObject ({firstName : "Saoirse",lastName : "Ronan",age : 26,});
person .on ("firstNameChanged", (newValue ) => {console .log (`firstName was changed to ${newValue }!`);});
With this, we can build something that errors when given the wrong property:
constperson =makeWatchedObject ({firstName : "Saoirse",lastName : "Ronan",age : 26});
person .on ("firstNameChanged", () => {});
// It's typo-resistentArgument of type '"firstName"' is not assignable to parameter of type '"firstNameChanged" | "lastNameChanged" | "ageChanged"'.2345Argument of type '"firstName"' is not assignable to parameter of type '"firstNameChanged" | "lastNameChanged" | "ageChanged"'.person .on ("firstName" , () => {});
Argument of type '"frstNameChanged"' is not assignable to parameter of type '"firstNameChanged" | "lastNameChanged" | "ageChanged"'.2345Argument of type '"frstNameChanged"' is not assignable to parameter of type '"firstNameChanged" | "lastNameChanged" | "ageChanged"'.person .on ("frstNameChanged" , () => {});
Inference with Template Literals
Note how the last examples did not re-use the type of the original value. The callback used an any
. Template literal types can infer from substitution positions.
We can make our last example generic to infer from parts of the string to figure out the associated property.
typePropEventSource <Type > = {on <Key extends string & keyofType >(eventName : `${Key }Changed`,callback : (newValue :Type [Key ]) => void ): void;};
declare functionmakeWatchedObject <Type >(obj :Type ):Type &PropEventSource <Type >;
constperson =makeWatchedObject ({firstName : "Saoirse",lastName : "Ronan",age : 26});
// ^ = (parameter) newName: stringperson .on ("firstNameChanged",newName => {
console .log (`new name is ${newName .toUpperCase ()}`);});
// ^ = (parameter) newAge: numberperson .on ("ageChanged",newAge => {
Here we made on
into a generic method.
When a user calls with the string "firstNameChanged'
, TypeScript will try to infer the right type for K
. To do that, it will match K
against the content prior to "Changed"
and infer the string "firstName"
. Once TypeScript figures that out, the on
method can fetch the type of firstName
on the original object, which is string
in this case. Similarly, when called with "ageChanged"
, TypeScript finds the type for the property age
which is .
Inference can be combined in different ways, often to deconstruct strings, and reconstruct them in different ways.
Intrinsic String Manipulation Types
Converts each character in the string to the uppercase version.
Example
typeGreeting = "Hello, world"type// ^ = type ShoutyGreeting = "HELLO, WORLD"ShoutyGreeting =Uppercase <Greeting >
typeASCIICacheKey <Str extends string> = `ID-${Uppercase <Str >}`type// ^ = type MainID = "ID-MY_APP"MainID =ASCIICacheKey <"my_app">
Lowercase<StringType>
Converts each character in the string to the lowercase equivalent.
Example
Converts the first character in the string to an uppercase equivalent.
Example
typeLowercaseGreeting = "hello, world";type// ^ = type Greeting = "Hello, world"Greeting =Capitalize <LowercaseGreeting >;
Uncapitalize<StringType>
Converts the first character in the string to a lowercase equivalent.
Example
typeUppercaseGreeting = "HELLO WORLD";type// ^ = type UncomfortableGreeting = "hELLO WORLD"UncomfortableGreeting =Uncapitalize <UppercaseGreeting >;
Technical details on the intrinsic string manipulation types
The code, as of TypeScript 4.1, for these intrinsic functions uses the JavaScript string runtime functions directly for manipulation and are not locale aware.
function applyStringMapping(symbol: Symbol, str: string) {
switch (intrinsicTypeKinds.get(symbol.escapedName as string)) {
case IntrinsicTypeKind.Uppercase: return str.toUpperCase();
case IntrinsicTypeKind.Lowercase: return str.toLowerCase();
case IntrinsicTypeKind.Capitalize: return str.charAt(0).toUpperCase() + str.slice(1);
case IntrinsicTypeKind.Uncapitalize: return str.charAt(0).toLowerCase() + str.slice(1);
}
return str;
`