#839·stitches

Add better typescript support for length units, colors and so on with the help of template literals

Author: joseDaKingCreated Oct 10, 2021Updated Dec 28, 2024
Labelsawaiting feedback

Is your feature request related to a problem? Please describe. It would be really nice if there is template type support for colors, length units, and other units. So it would become more typesafe Describe the solution you'd like

typescript
// IntelliSense will be lost
const marginX = (value: PropertyValue<"margin">) => ({
  marginLeft: value,
  marginRight: value
});

// The PropertyValue<"margin"> should support CSS units compatible with margin property
// In other words the PropertyValue<"margin"> should include the types bellow and it the string type should not be allowed
type Unit<T extends string> = `${number}${T}`; 

type CM = Unit<"cm">;

type MM = Unit<"mm">;

type IN = Unit<"in">;

type PX = Unit<"px">;

type PT = Unit<"pt">;

type PC = Unit<"pc">;

type Negative<T extends string> = `-${T}`;

type FixedLengthUnits = CM | MM | IN | PX | PT | PC;

type NegativeFixedLengthUnits = Negative<FixedLengthUnits>;

// Color types for color and backgroundColor properties
type RGB = `rgb(${number}, ${number}, ${number})`;

type RGBA = `rgba(${number}, ${number}, ${number}, ${number})`;

type HSL = `hsl(${number}, ${number}%, ${number}%)`;

type HSLA = `hsla(${number}, ${number}%, ${number}%, ${number})`;

type HEX = `#{string}`;

type Colors = RGB | RGBA | HSL | HEX;

The only downside is that if there are strict types for units it might prevent us from using CSS calc (because CSS calc can be typed with template literal types but it might be slow and not efficient). The following might not work

typescript
const styles: CSS = {
  width: "calc(50% - $32)"
};

Describe alternatives you've considered I could write all those types for myself but then I need to manage it on my own and I can only use them in utility functions and not in regular CSS properties. If it is not possible I can live with that, it is no big deal but I think it would make DX better.