Generate getter names
Deriving method or property names from string-literal keys.
TypeScript · Type Alias
Capitalize<StringType> converts the first character of a string-literal type to uppercase. It is an intrinsic compiler type commonly used with template literal and mapped types to generate names.
Capitalize<StringType> is an intrinsic string-manipulation type that changes the first character of a string literal type to uppercase while leaving the remainder unchanged. It is useful inside template literal types and mapped types when generating consistently named APIs.
Capitalize<StringType>| Name | Type | Description |
|---|---|---|
StringType | string type | String-literal type whose first character is converted to uppercase. |
A string-literal type with its first character converted to uppercase.
.d.ts files.type EventName = "userCreated" | "orderPlaced";
type GetterName = `get${Capitalize<EventName>}`;
const getter: GetterName = "getUserCreated";
console.log(getter);The type transforms each union member's first character, producing the allowed getter names.
Deriving method or property names from string-literal keys.
Creating consistent event, command, or route names from unions.
Building typed APIs whose names follow a casing convention.
Capitalize do?Capitalize<StringType> converts the first character of a string literal type to its uppercase equivalent. For example, Capitalize<"hello, world"> becomes "Hello, world".
Follow-up: How does it differ from Uppercase? Uppercase transforms every character, whereas Capitalize transforms only the first character.
Capitalize work with unions?It can transform each member of a string-literal union, so Capitalize<"foo" | "bar"> becomes "Foo" | "Bar". This makes it useful for deriving names without manually listing every result.
Follow-up: What happens with a non-literal string? The result cannot be narrowed to one concrete literal, so capitalization is most useful when the input retains literal information.
Capitalize help generate API property names?Capitalize is commonly embedded in template literal types, such as get${Capitalize<Property>} , to generate names like getName. Mapped types can use those generated names as property keys.
Follow-up: Why might a mapped type intersect a key with string? Object keys can also be numbers or symbols, while the capitalization operation applies to string cases.
UppercaseLowercaseUncapitalizeTemplate Literal TypesMapped Types