frenic / csstype

Strict TypeScript and Flow types for style based on MDN data
MIT License
1.7k stars 69 forks source link

Exact value validation #121

Closed martin-tichovsky-s2 closed 3 years ago

martin-tichovsky-s2 commented 3 years ago

I would like to ask if you consider exact value validation. CSS properties have exact defined form by W3, so for example the display property should have one of defined values like "contents" | "list-item" | "none" and so on. From my point of view the Display type should looks like this:

type Display = Globals | DataType.DisplayOutside | DataType.DisplayInside | DataType.DisplayInternal | DataType.DisplayLegacy | "contents" | "list-item" | "none";

Without string or (string & {}). I know that the type (string & {}) is only TypeScript hack for now, but to restrict the values only for one of these and use full potentional of TypeScript would be better to don't use string or (string & {}) in type definition. Because you can't give to the developers only restricted values and prevent possible mistakes and therefore TypeScript exists.

Since TypeSctipt 4.1 is possible even to check string format. So for example for size we can have exact value checking like so:

type Units = "cm" | "mm" | "in" | "px" | "pt" | "pc" | "%";
type Size = `${number}${Units}`;

let size: Size;
size = '15px'; // ok
size = '5%'; // ok
size = '15 dim'; // error

So with this new functionality we can check exact string format such as '2px solid #000', etc. With this, we can get rid of most strings and (string & {}) and check all CSS properties as CSS validator does.

Conclusion: My goal is to validate all values of CSS properties with TypeScript and prevent errors in CSS before run an application.

frenic commented 3 years ago

The display property has arbitrary string because it support multiple values (related https://github.com/frenic/csstype/issues/8). This is solvable with Template Literal Types as you mention and the plan is to use it for property values and CSS Custom Properties in the future in some extent. But I have some concerns along with this:

martin-tichovsky-s2 commented 3 years ago

Very good point, thanks. I will do some exploring and testing when I will have some time and I will come back with results.

martin-tichovsky-s2 commented 3 years ago

My exploring about this problem is, that TypeScript has limit for unions something up to 100 thousands, so basically it isn't enough even for validation color with hex format (#000000). And even when I was testing performance, IDE wasn't slow, but response time when object got underline was really high with complex unions up to 90 thousands. So thank you for comment, I'm closing this thread.