UPDATED FOR TS4.5+
Now that TypeScript supports tail recursion elimination on conditional types we can write Kebab<T>
in a straightforward way that should handle strings up to ~1000 characters:
type Kebab<T extends string, A extends string = ""> =
T extends `${infer F}${infer R}` ?
Kebab<R, `${A}${F extends Lowercase<F> ? "" : "-"}${Lowercase<F>}`> :
A
This works by iterating character-by-character, and inserting a "-"
before each character which is not already lowercase (so caseless characters like numbers will not get a dash before them), and then lowercasing each character.
Non-tail-recursive character-by-character iteration in TypeScript 4.5+, or any recursive type in TypeScript 4.4 and below hits recursion limits for modestly long strings, sometimes even strings of only twenty or so characters, and weird workarounds were required to handle longer strings. But now we can handle string literals longer than I imagine anyone would reasonably need:
type Testing = Kebab<"itWasTheBestOfTimesItWasTheWorstOfTimesItWasTheAgeOfWisdomItWasTheAgeOfFoolishnessItWasTheEpochOfBeliefItWasTheEpochOfIncredulityItWasTheSeasonOfLightItWasTheSeasonOfDarknessItWasTheSpringOfHopeItWasTheWinterOfDespair">
// type Testing = "it-was-the-best-of-times-it-was-the-worst-of-times-it-was-the-age-of-wisdom-it-was-the-age-of-foolishness-it-was-the-epoch-of-belief-it-was-the-epoch-of-incredulity-it-was-the-season-of-light-it-was-the-season-of-darkness-it-was-the-spring-of-hope-it-was-the-winter-of-despair"
Now we can use key remapping (also a TS4.1 feature) to easily convert from an object with camelCase keys to one with kebab-case keys:
type KebabKeys<T> = { [K in keyof T as K extends string ? Kebab<K> : K]: T[K] };
Finally, let's try it out on your example:
export interface CssPropertiesCamel {
alignContent: number | string | null;
alignItems: number | string | null;
alignSelf: number | string | null;
alignmentBaseline: number | string | null;
}
type CssPropertiesKebab = KebabKeys<CssPropertiesCamel>;
/* type CssPropertiesKebab = {
"align-content": number | string | null;
"align-items": number | string | null;
"align-self": number | string | null;
"alignment-baseline": number | string | null;
} */
export interface CssProperties extends CssPropertiesCamel, CssPropertiesKebab { }
Looks good! We've turned CssPropertiesCamel
into CssPropertiesKebab
, and then CssProperties
can just be a merged version of those two types.
Playground link to code